Intervals
Signal: the input is a list of [start, end] pairs (meetings, bookings, ranges, balloons), with questions about overlap, merging, inserting, removing the fewest to avoid conflicts, or counting simultaneous ones.
Core idea: sort, then sweep left to right, comparing each interval with the last one you kept. After sorting by start, two intervals [a, b] and [c, d] (with a ≤ c) overlap iff c ≤ b.
Which sort key?
| Goal | Sort by | Why |
|---|---|---|
| Merge overlapping / insert | start | Overlaps become adjacent |
| Keep the max number of non-overlapping intervals (or min removals, min arrows) | end | Finishing earliest leaves the most room (classic greedy proof) |
| Max simultaneous intervals (rooms needed) | separate starts and ends, or a min-heap of end times | Sweep line over events |
python
intervals.sort(key=lambda x: x[0])
merged = []
for s, e in intervals:
if merged and s <= merged[-1][1]: # overlaps the last kept interval
merged[-1][1] = max(merged[-1][1], e)
else:
merged.append([s, e])Clarify the boundary
Do [1, 4] and [4, 6] overlap? Problems differ (touching meetings usually don't conflict, but touching ranges usually merge). Ask, and use < vs <= accordingly.