Intervals
Sort by start or end, then sweep: merging, inserting, meeting rooms.
5 pages, free to read
- 1
Interval basics & overlap
BeginnerAn interval is a [start, end] range, and two intervals overlap exactly when each one starts before the other ends: a.start <= b.end and b.start <= a.end.
8 min read - 2
Merging intervals
IntermediateSort intervals by start, then sweep once: each interval either extends the last merged block or starts a new one, for O(n log n) total.
8 min read - 3
Inserting an interval
IntermediateTo insert a new interval into a sorted, disjoint list, copy everything that ends before it, absorb everything that overlaps it, then copy the rest: one pass, O(n).
8 min read - 4
Meeting rooms & the sweep line
IntermediateTo find how many intervals are active at once, turn each interval into a +1 start event and a -1 end event, sort the events, and sweep while keeping a running count; the peak is the answer.
10 min read - 5
Interval scheduling
IntermediateTo keep the most non-overlapping intervals, sort by end time and greedily take each interval that starts after the last one you took; earliest finish leaves the most room for the rest.
10 min read