Problem overview
The method merge receives intervals, a slice where each interval is a []int holding a start and an end. It merges every group of overlapping intervals and returns the intervals that remain, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5]. The input isn't sorted, and it has at least one interval.
For [[1,3],[2,6],[8,10],[15,18]] the answer is [[1,6],[8,10],[15,18]]: the first two overlap and the other two stand alone. For [[6,8],[1,9],[2,4],[4,7]] the answer is [[1,9]], because [1,9] covers all the rest.
Approach: sort, then grow the last merged interval
If the intervals are in random order, any interval might overlap any other, and comparing all pairs takes O(n²). After sorting by start, the intervals that overlap come one after another. Then one pass is enough.
Keep a slice merged of the results so far. Its last interval is the one that may still grow. For each interval in sorted order:
- If it starts after the last merged interval ends, it can't overlap anything so far, because every earlier interval ended even sooner. It becomes a new merged interval.
- Otherwise it overlaps the last one, and the last one's end becomes the larger of the two ends. The larger end matters: an interval can lie completely inside the last one, like
[2,3]inside[1,10], and then the end must stay 10.
Sorting costs O(n log n), and the merging pass is linear. Here is the pass on [[6,8],[1,9],[2,4],[4,7]], after sorting to [[1 9] [2 4] [4 7] [6 8]]:
after [1 9] -> [[1 9]]
after [2 4] -> [[1 9]]
after [4 7] -> [[1 9]]
after [6 8] -> [[1 9]]
Why is it enough to compare with only the last merged interval? Every interval in merged before it ends before the last one starts, because a gap was found at the moment the last one was created. The new interval starts at or after the last one's start, so it can't reach back past the last one into an earlier group. The last interval's end is the only boundary that can decide the question.
Step by step
- Sort
intervalsby start withsort.Slice. Its functionfunc(i, j int) boolreturns whetherintervals[i][0] < intervals[j][0]. - Create
mergedas an empty[][]int. It will hold the results in order of start. - Loop over the intervals with
range, ignoring the index with_. They arrive in order of start. - Name the two ends:
start, end := interval[0], interval[1]. - Test for a new group. If
mergedis empty, or the last merged interval's end is less thanstart, append a new[]int{start, end}and store the grown slice back inmerged. The test uses<, so touching intervals merge. - Otherwise extend the last interval. In the
elsebranch, set its end tomaxof its current end andend. - Return
merged. Every interval went into a group, in order of start.
The solution in Go
type Solution struct {}
func (this Solution) merge(intervals [][]int) [][]int {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
merged := [][]int{}
for _, interval := range intervals {
start, end := interval[0], interval[1]
if len(merged) == 0 || merged[len(merged)-1][1] < start {
merged = append(merged, []int{start, end})
} else {
merged[len(merged)-1][1] = max(merged[len(merged)-1][1], end)
}
}
return merged
}
The Go details worth a closer look:
appendreturns a slice. It may allocate a bigger array, so the result must be stored back:merged = append(merged, ...). Callingappendwithout assigning drops the new element.- An empty result is still a slice.
merged := [][]int{}creates an empty slice with length 0, ready forappend. Anilslice would work withappendtoo; this form just makes the intent clear. - Evaluating
len(merged)-1is safe because of||. Whenmergedis empty, the left side is true and Go doesn't evaluate the right side, so there is no read at index-1. - The new
[]int{start, end}is a copy. Extendingmerged[len(merged)-1][1]changes that new slice, not the caller's inner slices. The caller's outer slice is reordered by the sort, though:sort.Slicesorts in place. - The sort package. The lesson already imports
sort. In a file of your own, addimport "sort". The built-inmaxneeds no import since Go 1.21.
Complexity
Time: O(n log n). The sort dominates, and the merging pass makes n constant-time steps.
Space: O(n) for the result, which in the worst case, with no overlaps, holds a copy of every interval.
Edge cases and common mistakes
- Forgetting
max. Setting the end toenddirectly breaks on a contained interval:[[1,10],[2,3]]would become[[1,3]]instead of[[1,10]]. - Using
<=in the new-group test. Touching intervals then stay separate:[[1,4],[4,5]]returns[[1,4],[4,5]]instead of[[1,5]]. - Skipping the sort. Overlapping intervals might not be next to each other, and the last merged one isn't enough to compare with.
- Intervals with the same start.
[[1,4],[0,4]]sorts to[[0,4],[1,4]]and merges into[[0,4]]. - Changing the result. Each merged interval is a fresh
[]int, so assigning tomerged[0][1]afterwards doesn't touch the caller's inner slices. For[[1,3],[2,6]], setting the result's end to 99 leaves the input as[[1 3] [2 6]]. - A single interval or a zero-length one.
[[5,5]]returns[[5,5]]. - Already separate intervals such as
[[1,2],[3,4]]come back unchanged.
Testing
[[1,3],[2,6],[8,10],[15,18]]gives[[1,6],[8,10],[15,18]].[[1,4],[4,5]]gives[[1,5]].[[6,8],[1,9],[2,4],[4,7]]gives[[1,9]].[[5,5]]gives[[5,5]].[[1,10],[2,3]]gives[[1,10]].[[1,2],[3,4]]gives[[1,2],[3,4]].[[1,4],[0,4]]gives[[0,4]].
