The problem, in one line. Given a pile of start-and-end pairs in any order, return the fewest pairs that cover exactly the same ground. LeetCode 56.
The tell. Pairs with a start and an end, and a question about which ones run into each other. When the answer is a union or a gap, sort by start first.
The wrong first idea
Read the pairs in the order they arrive and widen the last result whenever the next one touches it.
On [[8, 10], [1, 3], [2, 6]] that fails. A later pair can land anywhere, so no result you built can be trusted. The careful repair compares every pair and repeats until nothing changes. That is about n times n over two comparisons, so 10,000 pairs is 50 million pair checks, and one pass is still not always enough.
The full walk-through, with both wrong versions run, is in Clinic #28: Merge Intervals. This card is its one-page summary.
The invariant
Sort by start, then walk once, holding the last stretch you built.
flowchart LR S["sorted: [1,3] [2,6] [8,10]"] --> A["[1,3]: first stretch"] A --> B["[2,6]: 2 <= 3, widen to [1,6]"] B --> C["[8,10]: 8 > 6, new stretch"]
The sentence that stays true every step: every stretch behind the one in my hand is final, and the one in my hand covers everything seen so far that touches it. Sorting is what makes that safe, because no later pair can start before the current one.
The solution
def merge(intervals):
out = []
for s, e in sorted(intervals): # sorted by start: a newcomer can only touch the last stretch
if out and s <= out[-1][1]:
out[-1][1] = max(out[-1][1], e) # stretch the end, never shrink it
else:
out.append([s, e])
return out
print(merge([[1, 3], [2, 6], [8, 10], [15, 18]]))
print(merge([[1, 4], [4, 5]]))
print(merge([[1, 10], [2, 3], [12, 13]]))
[[1, 6], [8, 10], [15, 18]]
[[1, 5]]
[[1, 10], [12, 13]]
func merge(intervals [][]int) [][]int {
sort.Slice(intervals, func(a, b int) bool { return intervals[a][0] < intervals[b][0] }) // by start
out := [][]int{}
for _, iv := range intervals {
if n := len(out); n > 0 && iv[0] <= out[n-1][1] {
out[n-1][1] = max(out[n-1][1], iv[1]) // stretch the end, never shrink it
} else {
out = append(out, []int{iv[0], iv[1]})
}
}
return out
}
Same three calls print [[1 6] [8 10] [15 18]], [[1 5]], [[1 10] [12 13]].
Complexity
- Time O(n log n): the sort dominates, and the walk after it is one pass.
- Space O(n) for the answer, plus whatever the sort uses.
Traps
- Setting the end to the newcomer’s end. With
[[1, 10], [2, 3]]the stretch shrinks to[1, 3]and the road from 3 to 10 vanishes. Take the larger end. - Writing
<instead of<=.[[1, 4], [4, 5]]shares the point 4 and must come back as[[1, 5]]. - Skipping the sort because the examples look ordered.
[[8, 10], [1, 3], [2, 6]]returns three stretches instead of two.
Next in the ladder
Insert Interval hands you a list that is already sorted and already merged, and asks you to add one more without sorting again.