Skip to content

Merge Intervals

Lesson 2 of 4 · 5 min

Merge Intervals

Step 1 of 8

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.

  1. If it starts at or before the open end, stretch that end to the larger of the two ends
  2. Sort the intervals by start
  3. Otherwise there is a gap, so open a new block with this interval
  4. Put the first interval in the output as the open block
  5. Walk the rest, comparing each start with the open block's end

Mini quiz

1 / 3

After sorting, when does the next interval merge into the open block?