Algorithms · Sort, then sweep

Merge Intervals

Merge overlapping time ranges into one.

The problem

Merge all overlapping intervals (ones that touch, like [1, 4] and [4, 5], count as overlapping) and return the result in order.

merge([[1, 3], [2, 6], [8, 10], [15, 18]])[[1, 6], [8, 10], [15, 18]]
merge([[1, 4], [4, 5]])[[1, 5]]
Sort, then sweep. Put things in order first. Tidying a messy calendar by laying the meetings out from morning to night.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def merge(intervals):take [start, end] pairs
result = []merged intervals so far
for start, end in intervals:for each interval
i = 0look through everything we have
while i < len(result):each merged interval
s, e = result[i]its start and end
if start <= e and s <= end:they overlap (or touch)?
start, end = min(s, start), max(e, end)grow into one interval
result.pop(i)remove the old one
else:no overlap
i += 1check the next one
result.append([start, end])add the (maybe grown) interval
return sorted(result)in order

Now ask: what if there were a billion?

Calendar apps merge everyone’s busy times like this to find a free slot for 20 people at once. Genome tools merge billions of DNA ranges the same way: sort, then sweep.

Aim for O(n log n)🧩 classic

Think it through

Sorted by start, which interval can the next one merge with?

  • Any of them
  • Only the last merged one
Show the answer

Only the last merged one. Sorted order means everything earlier is already finished. So you either stretch the last merged interval or start a new one.

[1, 4] and [2, 3]: merging them gives…

  • [1, 3]
  • [1, 4]
Show the answer

[1, 4]. Stretch to the bigger end, not the newest one: max(last end, this end). The classic bug in this puzzle.

Stuck? 3 nudges, smallest first
  1. If the intervals were sorted by start, an interval could only merge with the one you just finished.
  2. Sort them. Walk through, and either stretch the last merged interval or start a new one.
  3. for start, end in sorted(intervals): if start <= out[-1][1], stretch out[-1][1]; else append.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def merge(intervals):take [start, end] pairs
out = []merged intervals, in order
for start, end in sorted(intervals):walk through them from earliest start
if out and start <= out[-1][1]:overlaps the last merged one?
out[-1][1] = max(out[-1][1], end)stretch it
else:a gap
out.append([start, end])start a new interval
return outthe merged list

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with sort, then sweep