Module 15
Intervals
Ranges with a start and an end: detect overlaps, merge them, choose the most that don't clash, and count how many happen at once.
Interval problems describe meetings, bookings, delivery slots, CPU tasks and video segments. Almost every one is solved by sorting first: by start time to merge, by end time to choose greedily, or by turning intervals into start/end events for a sweep line.
The module defines overlap precisely (the off-by-one that breaks most solutions), then covers the three sorting strategies and when each applies.
Best after: Sorting and Divide & Conquer
Part 1
Learn the ideas
- 15.1What Overlap MeansTwo intervals overlap when each starts before the other ends. Decide whether touching endpoints count.10 min
- 15.2Sort by Start, Then MergeAfter sorting by start, overlapping intervals are neighbours, so one pass merges them.12 min
- 15.3Sort by End for Greedy ChoicesTo keep the most non-overlapping intervals, always pick the one that ends earliest: it leaves the most room for the rest.12 min
- 15.4Sweep Line: Counting What's ActiveTurn each interval into a +1 event at its start and a −1 at its end, sort events, and the running sum is how many are active.12 min
Part 2
Solve the problems
In order of difficulty. Each one shows the pattern it teaches.
The core interval technique: sort by start and extend the last block while intervals overlap.
When the list is already sorted and disjoint, one linear pass does it: copy before, merge the overlap, copy after.
Sort by start and check neighbours: any overlap means one person can't attend everything.
The maximum number of simultaneous intervals, with a min-heap of end times (or a sweep line).
Activity selection: sort by end, keep every interval compatible with the last kept, and remove the rest.
The same greedy from the other side: shoot at the earliest end, and that arrow bursts every balloon that started before it.
Two sorted interval lists walked with two pointers: the intersection is [max of starts, min of ends], then advance the one that ends first.