TRACK B · ALGORITHMmedium•NOVEMBER 2026•5 MIN
Sort & Sweep Intervals: Merging Overlapping Windows
Sort by start timestamp once, then resolve every overlap with a single linear sweep.
intervalssortingschedulingsweep-line
The core idea
Once intervals are sorted by start time, the next interval can ONLY overlap the last interval in your merged output—turning pairwise O(n²) comparisons into one O(n) sweep.
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING INTERVALS SIM...
What to say out loud
Canonical Python template
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
intervals.sort(key=lambda iv: iv[0])
out = [intervals[0][:]]
for s, e in intervals[1:]:
if s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e)
else:
out.append([s, e])
return out