Command Palette

Search for a command to run...

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.

Intermediate 4 lessons 7 problems ~45 min of lessons

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

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The core interval technique: sort by start and extend the last block while intervals overlap.

  2. When the list is already sorted and disjoint, one linear pass does it: copy before, merge the overlap, copy after.

  3. Sort by start and check neighbours: any overlap means one person can't attend everything.

  4. The maximum number of simultaneous intervals, with a min-heap of end times (or a sweep line).

  5. Activity selection: sort by end, keep every interval compatible with the last kept, and remove the rest.

  6. The same greedy from the other side: shoot at the earliest end, and that arrow bursts every balloon that started before it.

  7. Two sorted interval lists walked with two pointers: the intersection is [max of starts, min of ends], then advance the one that ends first.