Merge every overlapping interval. Sort by start, then either extend the last merged interval or start a new one.
▼The problem
Given a list of intervals [start, end], merge all the overlapping ones and return the non-overlapping intervals that cover the same ground.
Example (the original's, given unsorted): [[8,10], [1,3], [15,18], [3,5], [9,12], [2,6]] → [[1,6], [8,12], [15,18]].
def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
out = []
for start, end in intervals:
if not out or start > out[-1][1]:
out.append([start, end])
else:
out[-1][1] = max(out[-1][1], end)
return outTRY IT ON LEETCODE ▶The solution
def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
out = []
for start, end in intervals:
if not out or start > out[-1][1]:
out.append([start, end])
else:
out[-1][1] = max(out[-1][1], end)
return outTranscript
Merge Intervals. You get a list of intervals, each with a start and an end. Wherever two overlap, merge them into one, and return the list with no overlaps left.
Here are six: eight to ten, one to three, fifteen to eighteen, three to five, nine to twelve, and two to six. On a number line they fall into three groups, so the answer is one to six, eight to twelve, and fifteen to eighteen.
The slow way compares every pair: six intervals make fifteen pairs, and n make about n squared. Worse, each merge builds a longer interval that may now reach another one, so you scan again, pass after pass.
The trick is to sort by start. Then intervals that overlap sit next to each other. Sweep left to right with one open interval. If the next one starts at or before the open end, stretch the end. If it starts past the end, close the open interval and open a new one.
Let's sweep. One to three opens. Two starts before three, so the end stretches to six. Three to five sits inside, and the end stays six. Eight is past six: close one to six, and open eight to ten. Nine overlaps, so stretch to twelve. Fifteen is past twelve: close it, and open fifteen to eighteen. At the end, close that one too. Three intervals.
In code: sort by start, then loop. If the output is empty, or the start is past the last end, append a new interval. Otherwise, set the last end to the max of the two ends. That max matters: without it, three to five would cut six back down to five.
Sorting takes n log n time, and the sweep is one pass, so the total is O of n log n. The output can hold up to n intervals, so the space is O of n.
Sort by start, then sweep and stretch. That's Merge Intervals.