Intervals
An interval is a pair [start, end]. Almost every interval problem becomes easy once the
intervals are sorted by start: overlapping ranges end up next to each other, so one
left-to-right pass finishes the job. The sort makes it O(n log n).
When to reach for it
Section titled “When to reach for it”- The input is a list of ranges: meetings, bookings, segments, time slots.
- The question is “merge the overlaps”, “can these all fit?”, “how many at once?”, or “what is left over?”.
- The input is unsorted. Sort first, then sweep. Never compare every pair.
Two ranges overlap when a.start <= b.end and b.start <= a.end. After sorting by start,
this shrinks to one check: next.start <= current.end. Decide up front whether touching
ranges (end == start) count as overlapping. For merging they usually do. For rooms
they usually do not.
Merge vs count-concurrent:
- Merge (what is the combined coverage?): keep one running interval and extend its end.
- Count concurrent (how many overlap at the busiest moment?): treat each interval as two events, a start (+1) and an end (-1), and track the running total. This is the sweep line.
Template
Section titled “Template”# Merge: sort by start, extend or appendintervals.sort()merged = []for start, end in intervals: if merged and start <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], end) # max: the new one may be contained else: merged.append([start, end])
# Count concurrent: sweep sorted starts against sorted endsstarts, ends = sorted(s for s, e in intervals), sorted(e for s, e in intervals)rooms = e = 0for s in starts: if s < ends[e]: rooms += 1 # still busy: need another else: e += 1 # one finished: reuseProblems in this guide
Section titled “Problems in this guide”- Merge Intervals — sort by start, extend or append
- Meeting Rooms II — sweep sorted starts against sorted ends