Coding & data structures · Linear structures — lists, stacks, queues, and intervals

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.

24 min read Full lesson in the app Patterns: sort by start, sort by end, sweep line, event counting, greedy exchange argument

What you'll be able to do

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 ChannelPulse

The first module of every track is free to read on the web — see what's open in Coding & data structures.