Interval problems: sort and sweep
Sort intervals by start, then sweep left to right comparing each one with the last kept interval; for 'how many at once', sweep +1/−1 start and end events instead.
How it works
- After sorting, two intervals overlap when
next.start <= last.end; use<if touching ends don't count. - Merge: on overlap, set the end to the max of both ends; otherwise start a new interval.
- Meeting rooms: the peak of the +1/−1 running sum is the number of rooms needed.
- Most non-overlapping intervals: sort by end, keep each one that starts after the last kept end.
- Sorting dominates at O(n log n); inserting into a sorted, disjoint list is O(n), no sort.
Check yourself
Answer to mark it learned; your answers aren't scored.
A user has a 1–10 meeting and a 2–3 meeting, yet the free/busy view shows them busy only 1–3. The merge code sorts by start and, on overlap, sets last.end = next.end. What is the fix?
Go deeper
Solve it in Python 10
- Attend every meetingeasy
- Add a range to sorted rangesmedium
- Fewest bookings to cancelmedium
- Fewest meeting roomsmedium
- Free time shared by everyonemedium
- Combine overlapping rangesmedium
- Overlap of two schedulesmedium
- Ranges not inside anothermedium
- Most pay from gigs that don't clashhard
- Tightest range around each pointhard
Full explanation
Most interval problems get easy after one move: sort by start. Then the next interval can only overlap the last one you kept, and it does when next.start <= last.end (use < if touching ends don't count).
- Merge: if the next interval overlaps the last kept one, set the end to
max(last.end, next.end); otherwise append it. - Insert into a sorted, disjoint list: copy the intervals that end before the new one, merge every one that overlaps it, copy the rest. O(n), no sort.
- Meeting rooms (max concurrency): turn each interval into a +1 event at its start and a −1 at its end, sort, and keep a running sum. Its peak is the number of rooms.
- Most non-overlapping intervals (interval scheduling): sort by end and keep each interval that starts after the last kept end. Sorting by start is wrong here: one long early interval blocks many short ones.
The sort dominates: O(n log n).
Code Merge, meeting rooms (sweep) and interval scheduling
def merge(intervals):
out = []
for s, e in sorted(intervals): # sort by start
if out and s <= out[-1][1]: # overlaps the last kept interval
out[-1][1] = max(out[-1][1], e) # max: [1,10] swallows [2,3]
else:
out.append([s, e])
return out
def min_rooms(meetings):
events = []
for s, e in meetings:
events += [(s, 1), (e, -1)]
events.sort() # same time: -1 first, room freed
rooms = peak = 0
for _, delta in events:
rooms += delta
peak = max(peak, rooms)
return peak
def max_non_overlapping(intervals):
kept, last_end = 0, float("-inf")
for s, e in sorted(intervals, key=lambda iv: iv[1]): # sort by END
if s >= last_end: # starts at or after the last kept end
kept, last_end = kept + 1, e
return keptReal example
Meeting rooms: [0,30], [5,10], [15,20]. Events in time order: 0 +1, 5 +1, 10 −1, 15 +1, 20 −1, 30 −1. Running sum: 1, 2, 1, 2, 1, 0, so the peak is 2 rooms. Merge: [1,3], [2,6], [8,10], [15,18] becomes [1,6], [8,10], [15,18], because [2,6] starts at 2 ≤ 3 and stretches the end to 6.
Trade-offs +2 · −2
+ You gain
- One sort turns O(n²) pairwise overlap checks into a single O(n) pass.
- The +1/−1 sweep generalizes: peak concurrency, free slots, total covered length.
− You pay
- Endpoint semantics (closed vs half-open) cause off-by-one bugs.
- Re-sorting per query is too slow when bookings and overlap checks arrive live.
Use it when
Inputs are ranges (meetings, bookings, IP ranges, time windows) and the question is overlap, coverage, free gaps, concurrency or how many fit.
Avoid it when
Many live inserts and overlap queries: use a sorted map, an interval tree or a database constraint. 2-D rectangles need a sweep plus a tree, not a plain sort.
Numbers to know 3
- Merge, meeting rooms, scheduling: O(n log n) for the sort, then O(n).
- Insert into an already sorted, disjoint list: O(n), no sort.
- Meeting rooms: 2n events; the answer is the peak of the running sum.
Common pitfalls 3
- Merging without
max():[1,10]then[2,3]must stay[1,10], not shrink to[1,3]. - Undecided endpoints: do
[1,5]and[5,8]overlap? Break event ties to match (end before start if not). - Sorting by start to maximize non-overlapping intervals: one long early interval blocks many short ones.
Interview questions 3
Answer out loud first, then reveal.
How do you recognize an interval problem, and which sort do you use?Show answer
The input is start/end pairs and the question is about overlap, coverage, gaps or concurrency. I sort by start to merge, insert or find gaps, because then only the last kept interval can overlap the next. For the most non-overlapping intervals, or the fewest removals, I sort by end: finishing earliest leaves the most room. For concurrency I sort events, not intervals.
Meeting rooms: event sweep or min-heap?Show answer
Both are O(n log n). The heap version sorts meetings by start and keeps a min-heap of end times; if the earliest end is ≤ the new start, that room is free and I pop it. The largest heap size is the answer. The sweep is shorter and extends to 'when is the peak' or 'free slots'. I pick the heap when the interviewer wants actual room assignments.
Follow-up: millions of bookings, with inserts and overlap checks arriving live?Show answer
Re-sorting per request is O(n log n), too slow. In memory I keep bookings in a sorted map or interval tree keyed by start, so each insert and overlap check is about O(log n) plus the overlaps found. In a database I let it enforce the rule: PostgreSQL range types with an exclusion constraint (EXCLUDE USING GIST (during WITH &&)) reject overlapping bookings even under concurrent writes.