Merge Intervals
Step 1 of 8
output0
Four spans, already sorted by start: 1–3, 2–6, 8–10, 9–11.
The Idea
Sort by start, then hold exactly one block open.
If the next interval starts at or before the open block's end, they touch: stretch the end to whichever is larger. Otherwise there is a gap, so close the block and open a new one. Every interval is looked at once.
Real-World Example
A driver's tracked stops on a timesheet. Three overlapping GPS windows at the depot should read as one block of time at the depot, not three — the overlaps are noise from the sensor, and merging turns them into the fact you actually bill.
The Code
Your turn
Put the steps in the right order.
- If it starts at or before the open end, stretch that end to the larger of the two ends
- Sort the intervals by start
- Otherwise there is a gap, so open a new block with this interval
- Put the first interval in the output as the open block
- Walk the rest, comparing each start with the open block's end
Mini quiz
1 / 3