Chapter 09 - Intervals

Sort the intervals, then sweep them from left to right. Most interval problems end up there.

Coding Interview Patterns book cover with the Rust logo and a CHAP 09 label, the chapter on intervals

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 plain sort.
  • 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

Other chapters

All the chapters, with every problem, are listed on the series page.


Back to top

Published on: Dec 1 2026 at 10:00 AM | Last updated: Dec 1 2026 at 10:32 AM

Copyright © 1964-2026 - 40tude