Problem overview
The method merge(intervals: number[][]): number[][] receives intervals as [start, end] pairs, merges the ones that overlap, and returns what remains, 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 result is [[1,6],[8,10],[15,18]]: the first two overlap and become [1,6]. For the unsorted input [[6,8],[1,9],[2,4],[4,7]] the result is [[1,9]], because [1,9] covers all the others. The solution should run in O(n log n) time.
Approach: sort by start, then extend the last interval
Checking every interval against every other takes O(n²). Sorting by start makes the overlapping intervals come one after another, so a single pass is enough.
Keep a list merged of the results so far. Its last interval is the one that may still grow. For each interval in sorted order:
- If
mergedis empty, or the last merged interval ends before this interval starts, there is a gap. Nothing earlier can reach this interval either, since the intervals come sorted by start. Start a new merged interval. - Otherwise the two overlap. Extend the last merged interval so it ends at the larger of the two ends.
The larger end matters because an interval can lie completely inside the last merged one, like [2,3] inside [1,10]. Then the merged end must stay 10, not drop to 3.
Step by step
- Sort by start with
sort((first, second) => first[0] - second[0]). The sort is the slowest part,O(n log n); the merging is one pass. - Declare
mergedwithconst, typednumber[][], as an empty array.constis fine, because the array is changed, not replaced. - Loop with
for...ofoverintervals, destructuring each one into[start, end]. The body then never needs[0]or[1]on the current interval. - Test for a gap. The condition is
merged.length === 0 || merged[merged.length - 1][1] < start. If it holds, push a new array[start, end]. Use<, not<=, so touching intervals merge. - Otherwise extend. In the
elsebranch, set the end of the last merged interval toMath.maxof its current end andend. - Return
merged. Every interval went into a merged one, in order of start.
Here is the sweep for [[6,8],[1,9],[2,4],[4,7]]. After sorting the input is [[1,9],[2,4],[4,7],[6,8]], and merged evolves like this:
[1,9] [[1,9]]
[2,4] [[1,9]]
[4,7] [[1,9]]
[6,8] [[1,9]]
The first interval starts the list. Each later one starts at or before the current end, 9, and ends at or before it, so the merged end stays 9.
The solution in TypeScript
class Solution {
merge(intervals: number[][]): number[][] {
intervals.sort((first, second) => first[0] - second[0]);
const merged: number[][] = [];
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;
}
}
The TypeScript details worth knowing:
- Destructuring in
for...of.for (const [start, end] of intervals)unpacks each two-element array into twoconstvariables. The compiler types them asnumberfromnumber[][]. - Pushing a new array.
merged.push([start, end])creates a fresh array rather than reusing the input one. That matters because the next lines changemerged[merged.length - 1][1]in place: if the input array itself had been pushed, the caller's data would change. With the fresh copy, the input's inner arrays stay as they were, and for[[1,3],[2,6]]the first inner array is still the same object, still holding[1,3]. - The outer array is changed.
sortworks in place, so the caller'sintervalsends up sorted. Aftermerge([[3,4],[1,2]]), the input reads[[1,2],[3,4]]. Sort a copy with[...intervals].sort(...)if that matters. - The compare function is required. A bare
sort()compares the intervals as text, so[100,101]would come before[9,10]. - Types are erased.
number[][]checks nothing at run time.
Complexity
Time: O(n log n), where n is the number of intervals: the sort costs O(n log n) and the sweep O(n).
Space: O(n) for the merged list, which holds up to n intervals when none overlap, plus whatever the sort uses internally.
Edge cases and common mistakes
- Touching intervals.
[[1,4],[4,5]]gives[[1,5]]. A<=in the gap test would split them. - One interval inside another.
[[1,10],[2,3]]gives[[1,10]]. Setting the end to the current interval's end instead of usingMath.maxwould shrink it to 3. - Unsorted input.
[[2,3],[1,10]]gives[[1,10]]. Without the sort, the sweep starts with[2,3]and then extends it to[2,10], losing the earlier start 1. - A single interval.
[[5,5]]gives[[5,5]], since a zero-length interval is allowed. - Same start.
[[1,4],[0,4]]gives[[0,4]]. - No overlaps at all.
[[1,4],[5,6]]comes back unchanged. - Sorting without a compare function. It sorts as text and gives a wrong order for numbers of different lengths.
Testing
[[1,3],[2,6],[8,10],[15,18]]gives[[1,6],[8,10],[15,18]].[[1,4],[4,5]]gives[[1,5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1,9]].[[1,10],[2,3]]gives[[1,10]].[[1,4],[5,6]]gives[[1,4],[5,6]].[[5,5]]gives[[5,5]].
