Chapter 09 - Intervals
Sort the intervals, then sweep them from left to right. Most interval problems end up there.
This page is the entry point of chapter 9 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
Once the intervals are sorted by start, two consecutive intervals overlap if the second one starts before the first one ends. Merging, intersecting or counting overlaps then takes one pass. To know how many intervals overlap at the busiest moment, split every interval into a start event and an end event, sort the events, and count.
When to reach for it
- Meetings, bookings, time ranges, schedules.
- Merge, intersect or count overlapping ranges.
- The maximum number of things happening at the same time.
In Rust
intervals.sort_by_key(|i| i.0)sorts by start; tuples also compare lexicographically with a plainsort.- With half-open intervals, an end and a start at the same time do not overlap: process the end event first.
- A small struct with
#[derive(Debug, Clone, Copy)]reads better than(i32, i32)once the code grows.
Problems in this chapter
- p161 - Merge Overlapping Intervals: Merge Overlapping Intervals (Intervals), solved in Rust. Merge an array of intervals so there are no overlapping intervals.
- p166 - Identify All Interval Overlaps: Identify All Interval Overlaps (Intervals), solved in Rust. Return an vector of all overlaps between 2 arrays of intervals.
- p170 - Largest Overlap of Interval: Largest Overlap of Intervals (Intervals) solved in Rust: given an array of half-open intervals, find the maximum number that overlap at once.
Other chapters
All the chapters, with every problem, are listed on the series page.