Merge Intervals
Sort by start, then merge or count overlaps in one pass.
- active this step
- visited / done
Sort by start
The order becomes [1, 3], [2, 6], [8, 10], [15, 18].
VARIABLES
- current
- -
- merged
- []
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Sort intervals by start. Walk through them, extending the current interval while the next one overlaps and starting a new one when it doesn’t.
Why it matters
Once sorted, an interval can only overlap the one before it, so a single pass is enough.
Think of it like this
Merging calendar bookings: once they’re in time order, you only compare each with the previous one.
Use it when
- Merging overlapping ranges
- Inserting a new interval
- Counting rooms or resources needed at the same time
Avoid it when
- Intervals arrive live and must be queried as they come - use a sorted structure
- The data is points, not ranges
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Sort, then merge | O(n log n) | O(n) |
| Compare all pairs | O(n²) | O(n) |
| Rooms needed (sort starts and ends) | O(n log n) | O(n) |
Often confused with: greedy interval scheduling - it sorts by end time to pick the most non-overlapping intervals.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Sorting is O(n log n) and usually the dominant cost
- Ask whether touching ends like [1, 2] and [2, 3] count as overlapping
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Forgetting to sort first
- Setting the end to the new end instead of the max - [1, 10] then [2, 3] would shrink to [1, 3]
- Changing the caller’s list when it must stay intact
Edge cases to test
- An empty list
- One interval inside another
- Touching intervals like [1, 2] and [2, 3]
Knowledge check
Quick check to lock in the intuition.
Merging [1, 10] with the next interval [2, 3], what should the end be?
Practice
Apply what you just watched on real interview problems.