## DEV Community is a community of 607,586 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# LeetCode 56. Merge Intervals codingpineapple Updated on ・1 min read

# Given a collection of intervals, merge all overlapping intervals.

Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

Constraints:
intervals[i] <= intervals[i]

``````var merge = function(intervals) {
if(intervals.length <= 1) return intervals;
// sort the array so earlier start times are at the beginning
intervals = intervals.sort((a,b) => a - b)
let output = [intervals];
let current = output;
// If the current interval's end time is greater than or equal
// to the next interval's start time, then we know there is an
// overlap and we merge them.
// If there is no overlap, then we add the next interval to the
// list of intervals in our output array and repeat the process
// until we go through the entire list of intervals.
for(let i = 1; i< intervals.length;i++) {
const next = intervals[i]
if(current >= next) {
current = Math.max(current, next);
} else {
current = next;
output.push(current);
}
}
return output;
};

``````

## Discussion (0) 