Merge overlapping intervals
Sort by start, then one pass. The sort does the hard part.
By devskills editorial team · Last updated
The problem
Given intervals like [1,3] [2,6] [8,10], merge the ones that overlap: [1,6] [8,10].
Brute force first
Without sorting: keep comparing every pair of intervals. When two overlap, replace them with their union and start the scan again. Stop when a full pass merges nothing.
Each pass is O(n²) pairs and you may need n passes: O(n³) time worst case, O(n) space. Sorting turns it into one pass.
The approach
Sort by start time. Now an interval either overlaps the last merged one (its start is not after that end), so you extend it, or it starts a new merged interval. O(n log n) time for the sort, O(n) for the output.
package mainimport ( "fmt" "sort")// merge combines overlapping [start, end] intervals.// Sort by start, then each interval either extends the last one or starts a new one.func merge(in [][2]int) [][2]int { if len(in) == 0 { return nil } s := append([][2]int(nil), in...) // copy: do not reorder the caller's slice sort.Slice(s, func(i, j int) bool { return s[i][0] < s[j][0] }) out := [][2]int{s[0]} for _, cur := range s[1:] { last := &out[len(out)-1] // pointer, so we can grow it in place if cur[0] <= last[1] { last[1] = max(last[1], cur[1]) } else { out = append(out, cur) } } return out}func main() { fmt.Println(merge([][2]int{{8, 10}, {1, 3}, {2, 6}, {15, 18}})) // [[1 6] [8 10] [15 18]] fmt.Println(merge([][2]int{{1, 4}, {4, 5}})) // [[1 5]] fmt.Println(merge([][2]int{{1, 10}, {2, 3}})) // [[1 10]]}Dry run
[1,3] [2,6] [8,10] [15,18], already sorted by start:
| interval | last in out | overlap? | out after |
|---|---|---|---|
| [1,3] | (none) | - | [1,3] |
| [2,6] | [1,3] | 2 <= 3, yes, end = max(3,6) | [1,6] |
| [8,10] | [1,6] | 8 > 6, no | [1,6] [8,10] |
| [15,18] | [8,10] | 15 > 10, no | [1,6] [8,10] [15,18] |
Go-specific gotchas
- `sort.Slice` sorts in place. Copy first if the caller's slice must not change.
slices.SortFuncwithcmp.Compareis the newer way and also fine. - Take a pointer to the last element (
&out[len(out)-1]) to update it.last := out[len(out)-1]is a copy, so changing it does nothing. - `[2]int` is an array, a value type. It is copied on assignment, which is exactly why the pointer above is needed.
- Decide whether touching intervals (
[1,4]and[4,5]) merge. Here they do, because of<=. Ask.
Variant: merge intervals arriving on several channels
Some online assessments dress this problem up as concurrency: "process data from multiple channels and merge the overlapping intervals". There are two versions, and the first question to ask is whether each channel delivers its intervals sorted by start.
If the channels are unsorted, there is no shortcut: fan the channels into one (a goroutine per input channel, a WaitGroup, and one closer, as in Concurrency patterns), collect everything into a slice, then run the sort-and-sweep above. You cannot emit anything early, because the next value on any channel might start before everything you have seen.
If each channel is sorted by start, you can merge as a stream. Keep the next interval from each channel, always take the one with the smallest start, and extend or start a merged interval as before. As soon as the interval you take starts after the current merged end, the current one is final and can be sent on, because no input still to come can start earlier. That is a k-way merge: O(n·k) with a linear scan over k heads, or O(n log k) with container/heap when there are many channels.
package mainimport "fmt"type interval struct{ start, end int }// source sends its intervals, already sorted by start, then closes.func source(ivs ...interval) <-chan interval { ch := make(chan interval) go func() { defer close(ch) for _, iv := range ivs { ch <- iv } }() return ch}// mergeStreams reads channels that are each sorted by start, and sends a// merged interval as soon as no later input can extend it.func mergeStreams(ins ...<-chan interval) <-chan interval { out := make(chan interval) go func() { defer close(out) heads := make([]interval, len(ins)) alive := make([]bool, len(ins)) for i, in := range ins { heads[i], alive[i] = <-in // ok is false once a channel is closed } var cur interval have := false for { best := -1 // the stream whose next interval starts first for i := range ins { if alive[i] && (best < 0 || heads[i].start < heads[best].start) { best = i } } if best < 0 { break // every input is closed } iv := heads[best] heads[best], alive[best] = <-ins[best] switch { case !have: cur, have = iv, true case iv.start <= cur.end: cur.end = max(cur.end, iv.end) default: out <- cur // nothing still to come starts before iv.start: cur is final cur = iv } } if have { out <- cur } }() return out}func main() { a := source(interval{1, 3}, interval{8, 10}) b := source(interval{2, 6}, interval{15, 18}) c := source(interval{9, 12}) for iv := range mergeStreams(a, b, c) { fmt.Println(iv.start, iv.end) }}- Write interval merging with one sort and one pass.
- Explain why updating a copy of the last interval does nothing.
- Predict the merged output for a small input.
- Sort by start, then one pass.
- Extend the last interval or start a new one.
- Update through a pointer or index, not a copy.
merge(in [][2]int) [][2]int that merges overlapping intervals (touching ones like [1,4] [4,5] merge too) and returns them sorted by start. Example: [1,3] [8,10] [2,6] → [1,6] [8,10].Tab indents. Press Esc, then Tab, to leave the editor.
- 1The main task: Insert a new interval into an already sorted, non-overlapping list and merge as needed, in O(n) without sorting again.
- 2Dry run
[1,4] [2,3]. Why must the merge usemax(last end, new end)rather than just the new end? - 3Given meeting times, can one person attend all of them? (
[0,30] [5,10] [15,20]→ no.)