Back to All Questions
Merge Intervals
Netflix
Array
Sorting
Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example:
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].
Solution Walkthrough
Overlaps are only easy to detect once the intervals are in a predictable order — so the first move is always to sort by start time. After that, a single linear pass can merge everything.
- Sort
intervalsin ascending order by their start value. - Initialize the result with the first interval.
- For each subsequent interval, compare it against the last interval already placed in the result:
- If the current interval's start is less than or equal to that last interval's end, they overlap — extend the last interval's end to the maximum of the two ends.
- Otherwise, there's a gap — push the current interval onto the result as a new, separate interval.
The sort dominates the cost at O(n log n); the merge pass itself is a single O(n) sweep. Overall time complexity is O(n log n), with O(n) space for the result (or O(log n) to O(n) depending on the sort's implementation).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Related Algorithms