Problem overview
The method insert receives intervals, a slice of []int pairs (start, end) that is already sorted by start with no two intervals overlapping or touching, and one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result, still sorted and with no overlaps. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they merge into [1,5].
For [[1,3],[6,9]] and [2,5] the answer is [[1,5],[6,9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] the answer is [[1,2],[3,10],[12,16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so those four merge into [3,10]. With intervals = [] and [5,7], the answer is [[5,7]].
Approach: before, overlapping, after
The input is already sorted and free of overlaps, so there is no need to sort again or compare every pair. A single left-to-right pass handles it in O(n), because the intervals fall into three groups, in this order:
- Before. Intervals that end before the new one starts. They go into the answer unchanged.
- Overlapping. Intervals that start no later than the end of the growing new interval. They all merge with it. Each can only widen it, with an earlier start or a later end.
- After. The rest. They start after the merged interval ends, so none can overlap it, and they go into the answer unchanged.
One index i walks through the intervals once, and each loop picks up where the one before it stopped.
For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], [1,2] ends at 2, before 4, so it is in the first group. Then [3,5], [6,7] and [8,10] each start at 8 or earlier, the current end, so they merge: the start drops to 3 and the end grows to 10. [12,16] starts after 10 and lands in the third group.
Step by step
- Create
resultas an empty[][]int. - Store
len(intervals)innand start the indexiat 0. - Part one: a loop with only a condition, which is Go's
while. It runs whilei < nandintervals[i][1] < newInterval[0]. The test is<, because an interval ending exactly where the new one starts touches it, and touching intervals merge. - Inside it, append
intervals[i]toresult, keep whatappendreturns, and doi++. - Part two: keep the growing interval in
start, end := newInterval[0], newInterval[1]. - Loop while
i < nandintervals[i][0] <= end. Every interval left ends at or afternewInterval[0], so it overlaps exactly when it starts byend. Here<=is right, because one that starts exactly atendtouches it. - Set
starttomin(start, intervals[i][0]). - Set
endtomax(end, intervals[i][1]). The larger end matters when an interval lies fully inside the new one. - Move
ion withi++. Without it, the loop would look at the same interval forever. - Append the merged interval
[]int{start, end}toresult. If nothing overlapped,startandendare still the new interval's own, so it goes in unchanged. - Part three: loop while
i < n, as everything left starts afterend. - Append each remaining interval and do
i++. - Return
result.
The solution in Go
type Solution struct {}
func (this Solution) insert(intervals [][]int, newInterval []int) [][]int {
result := [][]int{}
n := len(intervals)
i := 0
for i < n && intervals[i][1] < newInterval[0] {
result = append(result, intervals[i])
i++
}
start, end := newInterval[0], newInterval[1]
for i < n && intervals[i][0] <= end {
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i++
}
result = append(result, []int{start, end})
for i < n {
result = append(result, intervals[i])
i++
}
return result
}
The Go details worth a closer look:
- Go has no
while. Aforwith only a condition does the same job:for i < n { ... }repeats as long as the condition holds. - Order inside
&&matters.&&stops at the first false operand, soi < ngoes first andintervals[i]is never read when the intervals have run out. With the two tests swapped, the read could go past the end and panic withindex out of range. appendmay reallocate. Always store its result back inresult.- Appended intervals are shared, not copied.
result = append(result, intervals[i])adds the same inner slice that the caller holds. Changingresult[0][0]afterwards also changes the caller's interval. The merged interval, built with[]int{start, end}, is new. - Built-in
minandmax. They exist since Go 1.21, with no import. The lessons use Go 1.22. - Multiple assignment with
:=.start, end := newInterval[0], newInterval[1]declares both in one statement.
Complexity
Time: O(n). The index i only moves forward and never steps back, so across the three loops each interval is handled once.
Space: O(n) for result, which holds up to n + 1 intervals.
Edge cases and common mistakes
- Touching intervals.
[[1,4]]with[4,5]gives[[1,5]]. If part one used<=, the interval[1,4]would be moved to the answer untouched and[4,5]would not merge with it. - Empty input. With no intervals, no loop runs except the append, and the answer holds only the new interval.
- A new interval before everything.
[[3,5]]with[1,2]gives[[1,2],[3,5]]. Part one is empty and the whole input lands in part three. - A new interval after everything.
[[1,5]]with[6,8]gives[[1,5],[6,8]]. - A new interval in a gap.
[[1,2],[5,6]]with[3,4]gives[[1,2],[3,4],[5,6]]. - A new interval inside an old one.
[[1,5]]with[2,3]gives[[1,5]], becausemaxkeeps the end at 5. - A new interval that covers everything.
[[1,2],[3,4]]with[0,10]gives[[0,10]]. - Forgetting
i++. The overlap loop never ends.
Testing
[[1,3],[6,9]],[2,5]gives[[1,5],[6,9]].[[1,2],[3,5],[6,7],[8,10],[12,16]],[4,8]gives[[1,2],[3,10],[12,16]].[],[5,7]gives[[5,7]].[[1,4]],[4,5]gives[[1,5]].[[1,2],[5,6]],[3,4]gives[[1,2],[3,4],[5,6]].[[1,2],[3,4]],[2,3]gives[[1,4]].[[1,2],[3,4]],[0,10]gives[[0,10]].
