Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
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] overlap, 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.
Example 3:
Input: intervals = [[4,7],[1,4]]
Output: [[1,7]]
Explanation: Intervals [1,4] and [4,7] are considered overlapping.
Constraints:
1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
Solutions
Solution 1: Sorting + One-pass Traversal
Thinking
The first idea is to pick an interval and scan the rest for overlaps, merging until nothing changes. Correct, but worst-case \(O(n^2)\) with a messy merge order. \(n \le 10^4\) is tight.
The waste is locating overlaps in unsorted input. After sorting by left endpoint, an interval can overlap only the interval we have not closed yet—later starts are larger, so they cannot skip over the middle and overlap again.
So we sort, then scan once, keeping \(\textit{st}, \textit{ed}\) as the interval under merge.
We can sort the intervals in ascending order by the left endpoint, and then traverse the intervals for merging operations.
The specific merging operation is as follows.
First, we add the first interval to the answer. Then, we consider each subsequent interval in turn:
If the right endpoint of the last interval in the answer array is less than the left endpoint of the current interval, it means that the two intervals will not overlap, so we can directly add the current interval to the end of the answer array;
Otherwise, it means that the two intervals overlap. We need to use the right endpoint of the current interval to update the right endpoint of the last interval in the answer array, setting it to the larger of the two.
Finally, we return the answer array.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Here, \(n\) is the number of intervals.
Solution 1 is already \(O(n \log n)\) and correct. It still keeps a separate \(\textit{st}, \textit{ed}\), writes only when the interval closes, and appends once more at the end.
What it lacks is storing the current interval in the answer: put the first interval into \(\textit{ans}\) immediately, then either extend \(\textit{ans}[-1]\)'s right end or append. Fewer variables, no final flush.
Solution 2 already mutates the last interval in the answer. The loop is still "look at one, patch if needed."
What it lacks is merging by groups: fix left \(l\), eat every overlapping interval in an inner loop while stretching \(r\), then push \([l, r]\) once. Already-written answers are never rewritten.