Problem overview
The method merge receives intervals, an array of [start, end] pairs in any order. It combines every group of overlapping intervals into one and returns the result sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5].
For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]]: the first two overlap and the others stand alone. For [[6,8],[1,9],[2,4],[4,7]] the input isn't sorted, and [1,9] covers all the others, so the answer is [[1,9]]. The lesson asks for O(n log n) time.
Approach: sort by start, then extend the last interval
Comparing every interval with every other one would be O(n²). Sorting by start removes the need: after it, intervals that overlap sit next to each other, so a single left-to-right pass can build the answer.
Keep a list merged. For each interval in order, look at the last interval in merged, the one still growing:
- If the current interval starts after that one ends, nothing so far can overlap it, so it begins a new merged interval.
- Otherwise it overlaps (or touches) the last one, so extend the last one's end to cover it.
The extension uses the larger of the two ends, not simply the new end, because an interval can lie completely inside the last merged one. Merging [2,3] into [1,10] must leave the end at 10.
Step by step
- Sort
intervalsby start with a compare function(first, second) => first[0] - second[0]. The negative result puts the smaller start first. - Declare
mergedwithconstas an empty array. Its last element is always the interval that may still grow. - Loop with
for...of, destructuring each interval into[start, end], so the body doesn't need[0]and[1]. - Check whether a new merged interval begins:
merged.length === 0or the last merged end is less thanstart. Then push a new array[start, end]. Use<here and not<=, since an interval that starts exactly where the last one ends touches it and has to merge. - Otherwise, in the
elsebranch, set the end of the last merged interval toMath.maxof its own end andend. - Return
merged. Every interval went into one of them, and they are in order of start.
The solution in JavaScript
class Solution {
merge(intervals) {
intervals.sort((first, second) => first[0] - second[0]);
const merged = [];
for (const [start, end] of intervals) {
if (merged.length === 0 || merged[merged.length - 1][1] < start) {
merged.push([start, end]);
} else {
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], end);
}
}
return merged;
}
}
Some JavaScript details matter here:
- The compare function is required.
sort()with no argument compares elements as strings, which would put[10,12]before[2,4]. It also sorts in place, so the caller'sintervalsarray ends up reordered. - Destructuring in
for...of.const [start, end] = intervalcopies the two numbers out of each pair. - Pushing a new array.
merged.push([start, end])creates a fresh pair, so extendingmerged's last interval later doesn't change the arrays inintervals. For[[1,3],[2,6]], the input still holds[[1,3],[2,6]]after the call, even if the returned[1,6]is edited afterwards. - The last element.
merged[merged.length - 1]is the last item. Reading it whenmergedis empty would giveundefined, and indexing into that throws aTypeError, which is why themerged.length === 0test comes first. The||stops as soon as it is true.
Why only the last merged interval matters
Because the intervals are sorted by start, every later interval starts at or after the current one. If it doesn't reach the last merged interval, it can't reach any earlier one, since those end even sooner than the last one begins. That is why one comparison per interval is enough, and why the pass never looks back.
Walking through the first example
For [[1,3],[2,6],[8,10],[15,18]] the input is already sorted. [1,3] goes into merged because the list is empty. [2,6] starts at 2, which is not after the last end (3), so the last interval's end becomes Math.max(3, 6), which is 6. [8,10] starts after 6, so it is pushed, and so is [15,18]. The result is [[1,6],[8,10],[15,18]].
The merged intervals in merged are disjoint and ordered: each new one begins strictly after the previous one ends. So the array is already sorted by start when the loop finishes, and nothing needs sorting a second time. Equal starts cause no trouble either: when two intervals start at the same point, the compare function returns 0, and either order produces the same merged result.
Complexity
Sorting is O(n log n) and the pass is O(n), so the time is O(n log n). The merged array holds up to n intervals, so the extra space is O(n), plus whatever the sort uses internally.
Edge cases and common mistakes
- One interval.
[[5,6]]returns[[5,6]]. - Touching intervals.
[[1,4],[4,5]]must give[[1,5]]. With<=in the new-interval test, the result is[[1,4],[4,5]]. - An interval inside another.
[[1,10],[2,3]]gives[[1,10]]. Setting the end toendwithoutMath.maxwould give[[1,3]]. - Unsorted input.
[[1,4],[0,4]]gives[[0,4]]only because of the sort. - A late interval that bridges many.
[[2,3],[4,5],[6,7],[8,9],[1,10]]sorts[1,10]to the front, and everything merges into[[1,10]].
Testing
Results from the reference solution:
[[1,3],[2,6],[8,10],[15,18]] -> [[1,6],[8,10],[15,18]]
[[1,4],[4,5]] -> [[1,5]]
[[6,8],[1,9],[2,4],[4,7]] -> [[1,9]]
[[1,2],[3,4]] -> [[1,2],[3,4]]
[[1,4],[0,4]] -> [[0,4]]
