Merge Intervals
The key idea
Sort the intervals by their start value. Then scan left to right: an interval overlaps the last merged one exactly when its start is less than or equal to that interval's end. If it overlaps, extend the end; otherwise it begins a new block.
Problem
You are given an array 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.
Two intervals overlap when one starts before or exactly where the other ends, so [1,4] and [4,5] count as overlapping and merge into [1,5].
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4
Examples
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Complexity
Time: O(n log n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Intervals problems
- Insert IntervalMEDIUM
- Meeting RoomsEASY
- Non-overlapping IntervalsMEDIUM