DSA problem
Merge Intervals
Given an array of intervals intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all of the intervals in the input.
Two intervals overlap when one starts at or before the other ends. After merging, the resulting list must contain no overlaps and must collectively cover every point that was inside any original interval. The order of the output intervals is sorted by start time.
The crucial observation is that overlapping intervals form connected components on the number line, and once you sort by start time these components appear as contiguous runs of the sorted list. That means a single pass after sorting is enough — no pairwise comparison, no graph, no extra data structure.
The optimal approach sorts by start, then walks through the sorted list maintaining a "current" merged interval. For each new interval, if its start is less than or equal to the current end, extend the current end to the max of the two; otherwise close the current interval (append it to the result) and start a new current. Sorting dominates at O(n log n) time; the sweep is O(n) and uses O(1) auxiliary space beyond the output.
Examples
intervals = [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]intervals = [[1,4],[4,5]][[1,5]]intervals = [[1,4],[2,3]][[1,4]]Constraints
- 1 <= intervals.length <= 10^4
- intervals[i].length == 2
- 0 <= start_i <= end_i <= 10^4
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.