IntermediateGreedy & Intervals

Intervals: sort by start, then sweep

Sort by start. Then each one either overlaps the last merged interval (extend it) or starts a new one.

The idea

Unsorted intervals can overlap in any order. Once sorted by start time, an interval can only overlap the most recent merged one, so a single pass decides everything.

Overlap test after sorting: the new start is ≤ the last end.

Worked example

[[1,3], [8,10], [2,6], [15,18]]

  1. sorted → [1,3], [2,6], [8,10], [15,18]
  2. [1,3] + [2,6] overlap (2 ≤ 3) → [1,6]
  3. [8,10] starts after 6 → new; [15,18] → new → [[1,6], [8,10], [15,18]]

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

sort intervals by start
merged ← empty
for each (start, end):
if merged isn't empty and start ≤ end of the last merged:
last end ← max(last end, end)(overlap: stretch it)
else:
add (start, end) to merged
return merged

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

intervals = [[1, 3], [8, 10], [2, 6], [15, 18]]

sorted

01–3
12–6
28–10
315–18

Solution · Pythonline 2

def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
merged = []
for start, end in intervals:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged

Step 1 of 6· line 2

Sort by start: [[1, 3], [2, 6], [8, 10], [15, 18]]. Now anything that overlaps the last merged interval comes right after it.

for the sort, for the sweep.

How to spot it

  • Meetings, ranges, schedules, “overlapping”, “insert an interval”.

Common mistakes

  • Setting the end to the new end instead of the max (a long interval can contain later ones).
  • Forgetting to sort.

Practise the ideas first

Practise it

Go further