Skip to content
TOPIC · 9 PROBLEMS · 4 PATTERNS

Intervals

Pairs of start and end. Meetings, bookings, ranges of numbers. Sort them by where they start and most of the work is done.

How to spot a interval problem

“[start, end]”The input is a list of pairs that each cover a stretch of a line, whether that is time, positions or numbers.
“overlapping”Merge them, count them, or remove some until none touch. Two intervals overlap when each starts before the other ends.
“at the same time”How many things are running at once, or how many rooms you need. Only the moments where something starts or ends matter.

Four patterns cover almost everything

Sort and merge

O(n log n)

Sort by start. Walk through, and either stretch the last merged interval or start a new one.

Reach for it when you need to combine overlaps or slot a new interval into a list.

Greedy by end

O(n log n)

Sort by end. Keep whichever interval finishes first, since it leaves the most room for the rest.

Reach for it when you want the most intervals that do not overlap, or the fewest removals or points to cover them all.

Sweep line

O(n log n)

Turn each interval into a +1 at its start and a -1 at its end. Walk the events in order and keep a running total.

Reach for it when you need how many intervals are active at once, or whether some limit is ever passed.Go deeper: Prefix sums: any range total in one subtraction

Sort + heap

O(n log n)

Sort the intervals and the queries. As you move forward, push intervals that have started and pop ones that have ended.

Reach for it when each query needs the best interval that covers it, or the earliest one to finish.Go deeper: How a heap always knows the smallest

The one template to memorise

Sort by start, then merge as you go. Nearly every interval problem begins with these few lines and changes what happens on an overlap.

solution.py
def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
merged = []
for start, end in intervals:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end) # overlaps: stretch it
else:
merged.append([start, end])
return merged

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Teemo AttackingSort and mergeEasyRead
2Summary RangesSort and mergeEasyRead
3Merge IntervalsSort and mergeMediumRead
4Insert IntervalSort and mergeMediumRead
5Non-overlapping IntervalsGreedy by endMediumRead
6Minimum Number of Arrows to Burst BalloonsGreedy by endMediumRead
7Car PoolingSweep lineMediumRead
8Find Right IntervalSort + binary searchMediumRead
9Minimum Interval to Include Each QuerySort + heapHardRead
Next upTreesGraphs