Sort and merge
O(n log n)Sort by start. Walk through, and either stretch the last merged interval or start a new one.
Reach for it when you need to combine overlaps or slot a new interval into a list.Pairs of start and end. Meetings, bookings, ranges of numbers. Sort them by where they start and most of the work is done.
Sort by start. Walk through, and either stretch the last merged interval or start a new one.
Reach for it when you need to combine overlaps or slot a new interval into a list.Sort by end. Keep whichever interval finishes first, since it leaves the most room for the rest.
Reach for it when you want the most intervals that do not overlap, or the fewest removals or points to cover them all.Turn each interval into a +1 at its start and a -1 at its end. Walk the events in order and keep a running total.
Reach for it when you need how many intervals are active at once, or whether some limit is ever passed.Go deeper: Prefix sums: any range total in one subtractionSort the intervals and the queries. As you move forward, push intervals that have started and pop ones that have ended.
Reach for it when each query needs the best interval that covers it, or the earliest one to finish.Go deeper: How a heap always knows the smallestSort by start, then merge as you go. Nearly every interval problem begins with these few lines and changes what happens on an overlap.
| # | Problem | Pattern | Difficulty | Solution |
|---|---|---|---|---|
| 1 | Teemo Attacking | Sort and merge | Easy | Read |
| 2 | Summary Ranges | Sort and merge | Easy | Read |
| 3 | Merge Intervals | Sort and merge | Medium | Read |
| 4 | Insert Interval | Sort and merge | Medium | Read |
| 5 | Non-overlapping Intervals | Greedy by end | Medium | Read |
| 6 | Minimum Number of Arrows to Burst Balloons | Greedy by end | Medium | Read |
| 7 | Car Pooling | Sweep line | Medium | Read |
| 8 | Find Right Interval | Sort + binary search | Medium | Read |
| 9 | Minimum Interval to Include Each Query | Sort + heap | Hard | Read |