PatternTime O(n log n) · Space O(n)7 min read
Intervals: sort by start, then sweep
Merging, inserting and counting overlapping ranges: calendar and meeting-room problems all start with the same move.
In short
Sort by start, then walk once. An interval either overlaps the last one (extend its end with max) or starts a new group. Cost: O(n log n) for the sort, O(n) for the sweep.
Merge overlapping intervals
Two intervals overlap when the second starts before (or exactly when) the first ends. After sorting by start, you only ever need to compare with the last interval in the result.
Merge intervals: sort, then sweep
Intervals
Speed
1def merge(intervals):2 intervals.sort(key=lambda x: x[0])3 out = [intervals[0]]4 for start, end in intervals[1:]:5 if start <= out[-1][1]:6 out[-1][1] = max(out[-1][1], end)7 else:8 out.append([start, end])9 return out
Intervals can arrive in any order. Sort them by start so overlapping ones end up next to each other.
Variables
n5
Step 1/11· Merges: 0
After sorting by start, an interval either overlaps the last result (extend its end) or starts a new one.
The family of problems
| Problem | Twist |
|---|---|
| Merge intervals | Extend the last end with max |
| Insert interval | Add the pieces before, merge the overlapping ones, add the pieces after |
| Non-overlapping intervals | Greedy: keep the one that ends earliest, count the removed |
| Meeting rooms II | Sort starts and ends separately (or use a min-heap of end times); the max concurrent is the answer |
Key takeaways
- 01Sort by start so overlapping intervals are neighbours.
- 02Compare each interval with the last one in the result.
- 03Extend with max(end, newEnd): never just copy the new end.
- 04Cost: O(n log n) for the sort, O(n) for the sweep.
Check your understanding
1 of 3
What's the first step to merge intervals?
Related topics