Intervals
Problems about ranges such as meetings, bookings and time slots: merging them, finding overlaps and counting how many run at once. Sorting, then one pass, solves most of them.
Overview
An interval is a pair [start, end]. Checking every pair of intervals for overlap costs O(n²). Almost every interval problem is solved faster by putting the intervals in order first. After sorting, intervals that can overlap sit next to each other, so one pass over the list is enough. The sort costs O(n log n) and dominates.
What changes from problem to problem is the sort key and what the pass does. Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
Every one of these rests on a single test: do two intervals overlap?
When do two intervals overlap?
The rule: two intervals [a, b] and [c, d] overlap when each one starts before the other ends. It is easier to remember the opposite: they do not overlap when one ends before the other starts.
So the test is two questions. First, does the first interval end (b) before the second starts (c)? If yes, there is no overlap. If not, does the second end (d) before the first starts (a)? If yes, again there is no overlap. If neither is true, they overlap, and the shared part runs from max(a, c) to min(b, d).
The one question to settle is whether touching counts. Meetings [1, 2] and [2, 3] can share a room, because the first ends as the second starts. Closed ranges of integers such as [1, 2] and [2, 3] do share the point 2. These are two models.
- Half-open, like meetings: the start is included and the end is excluded, so the test is a [!WARNING] > Mixing up < and <= is the most common bug in this topic. Settle whether touching counts before you write the test.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio