Builds onSorting as a tool
01The idea
An interval is a stretch with a start and an end, such as a meeting from 9 to 11. Interval problems are about how stretches relate: do they overlap, what do they share, how many run at the same time?
Two facts carry most of the work.
First, two intervals overlap when each one starts before the other one ends:
a.start < b.end and b.start < a.end
Second, the part they share runs from the later start to the earlier end:
start = max(a.start, b.start)
end = min(a.end, b.end)
If start < end, that span is the overlap. If not, they share nothing.
The other habit is to sort by start time first. Once intervals are in start order, an interval can only overlap the ones right before it that have not ended yet. You walk the list once and compare each interval with a running end time instead of with every other interval.
Decide early whether touching counts. Does a meeting from 1 to 3 clash with one from 3 to 5? Problems differ. The choice is the difference between < and <=.
02How to spot it
You are in an interval problem when the input is a list of pairs such as [start, end], and the question is about:
- overlaps, clashes or conflicts between them
- time that two schedules share, or time that nobody covers
- how many intervals are active at once, such as the number of rooms needed
- removing the fewest intervals so the rest do not overlap
The first step is almost always to sort by start. Some greedy problems sort by end instead, because the interval that ends first leaves the most room for the rest.
To count how many intervals are active at each moment, split each interval into a start event and an end event. Sort the events, then walk them with a counter. That is called a sweep line.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue