Intervals: sorting is the algorithm
Interval questions are hard for one reason — six ways two intervals can overlap, and code that enumerates them is unreadable and wrong — and they become easy for one reason: sorting collapses those six cases into one comparison, with the twist that merging wants them sorted by start and selection wants them sorted by end, for reasons you can prove.
What you'll be able to do
- Write the overlap predicate correctly for both closed and half-open intervals, and know which question to ask before writing it
- Prove why sorting by start reduces merging to a single comparison against the last kept interval
- Insert one interval into a sorted list in O(n) with the three-phase pattern, no re-sorting
- Solve the minimum-rooms problem two ways — a heap of end times and a +1/-1 event sweep — and get the endpoint tie-break right
- Explain why maximum non-overlapping selection sorts by end, using an exchange argument
Before this: prefix-sums, stacks-and-queues
The rest of this lesson is in the app
Interval questions are hard for one reason — six ways two intervals can overlap, and code that enumerates them is unreadable and wrong — and they become easy for one reason: sorting collapses those six cases into one comparison, with the twist that merging wants them sorted by start and selection wants them sorted by end, for reasons you can prove. This walkthrough runs about 24 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.