Problem overview
The method insert receives intervals, an array of [Int] pairs (start and end) that is already sorted by start and has no two intervals overlapping, plus one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result, still sorted and without overlaps. Two intervals overlap when they share at least one point, so touching intervals like [1,4] and [4,5] merge into [1,5]. There can be up to 100,000 intervals, and the method must run in O(n) time.
For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1, 5], [6, 9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] it is [[1, 2], [3, 10], [12, 16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so all four merge into [3, 10]. With no intervals and [5,7] the result is [[5, 7]].
Approach: before, overlapping, after
Because the input is already sorted and free of overlaps, there is no need to sort or to compare every pair. Walk through the intervals once, with an index i that carries over from one part to the next. Relative to newInterval they fall into three groups, in this order:
- Intervals that end before the new one starts. They can't overlap it and go into the result unchanged. The test is
intervals[i][1] < newInterval[0]. An interval that ends exactly at the new start touches it, so it belongs to the next group. - Intervals that overlap the new one. They all merge with it into one interval. Keep the growing interval in two variables,
startandend, beginning with the new interval's values. An interval overlaps it as long as it starts at or beforeend:intervals[i][0] <= end. Each one can lowerstartor raiseend. - The remaining intervals. Each one starts after
end, so none can overlap the merged interval. They go into the result unchanged.
Between the second and third groups, the merged interval [start, end] is appended, so the result stays sorted by start.
For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], group 1 is [1,2]. Group 2 starts with start = 4, end = 8. Reading [3,5] gives start = 3 and end = 8. Reading [6,7] changes nothing, because it lies inside. Reading [8,10] gives end = 10. The next interval, [12,16], starts after 10, so group 3 is [12,16]. A real run gives [[1, 2], [3, 10], [12, 16]].
Each interval is looked at once, so the time is O(n).
Step by step
- Create
resultwithvaras an empty[[Int]]. - Store
intervals.countinn, and create the indexiwithvarat 0. The index only moves forward, and each part continues where the previous one stopped. - Part one: a
whileloop that runs whilei < nandintervals[i][1] < newInterval[0]. Puti < nfirst:&&stops evaluating there when the intervals run out, beforeintervals[i]is read. - Copy and advance. Inside the loop,
appendintervals[i]toresultand doi += 1. - Start the merged interval. After the loop, declare
startandendwith onevar, set fromnewInterval[0]andnewInterval[1]. They arevars because they change as intervals merge in. - Part two: a second
whileloop that runs whilei < nandintervals[i][0] <= end. Use<=, because an interval that starts exactly atendtouches the merged one and must merge. - Lower the start inside it:
start = min(start, intervals[i][0]). Only the first overlapping interval can start before the new one. - Raise the end:
end = max(end, intervals[i][1]). The larger value is needed because an interval can lie entirely inside the merged one. - Advance with
i += 1. Without it, the loop would look at the same interval forever. - Append the merged interval
[start, end]toresultafter the loop. If nothing overlapped, it is the new interval unchanged. - Part three: a
whileloop that runs whilei < n. - Copy and advance as in part one.
- Return
result.
The solution in Swift
class Solution {
func insert(_ intervals: [[Int]], _ newInterval: [Int]) -> [[Int]] {
var result: [[Int]] = []
let n = intervals.count
var i = 0
while i < n && intervals[i][1] < newInterval[0] {
result.append(intervals[i])
i += 1
}
var start = newInterval[0], end = newInterval[1]
while i < n && intervals[i][0] <= end {
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
}
result.append([start, end])
while i < n {
result.append(intervals[i])
i += 1
}
return result
}
}
The Swift details worth a closer look:
- Short-circuit
&&. Ini < n && intervals[i][1] < newInterval[0], the right side runs only wheni < nis true. Reading an array outside its bounds stops the program, so the order of the two conditions matters. - No parentheses around conditions. Swift's
whileandifdon't need them, but braces are always required. var start = ..., end = .... Onevardeclares both variables. They are separate values: changingstartdoesn't affectend.minandmax. These are global functions that take two values of the same type.- Arrays of arrays are values.
result.append(intervals[i])adds a copy of that inner array, not a shared reference, and the caller'sintervalsis never changed. - Why
whileand notfor. The index must carry over from one loop to the next, and each loop decides on its own when to stop. Threewhileloops sharingiexpress that directly. - Parameter labels. Both parameters are declared with
_, so the call isinsert(intervals, newInterval)with no labels.
Complexity
Time: O(n). The three loops share one index that only increases, so each interval is read once, and every step does constant work.
Space: O(n) for the output. Besides the result, which can hold n + 1 intervals, the method uses only a few variables.
Edge cases and common mistakes
- No intervals.
[]with[5,7]gives[[5, 7]]: all three loops are skipped and only the append runs. - New interval before everything.
[[3,5]]with[0,1]gives[[0, 1], [3, 5]]. - New interval after everything.
[[3,5]]with[7,8]gives[[3, 5], [7, 8]]. - Inside an existing interval.
[[1,5]]with[2,3]gives[[1, 5]]. Themaxkeeps the end at 5. - Touching on one side.
[[1,3]]with[3,6]gives[[1, 6]], and[[1,2],[3,4]]with[2,3]gives[[1, 4]]. - Covering everything.
[[1,2],[6,7]]with[0,10]gives[[0, 10]]. - Strict versus non-strict comparisons. Part one uses
<and part two uses<=. Swapping either one would keep touching intervals apart. - Forgetting
i += 1. Awhileloop without it never ends. - Appending the merged interval too early or too late. It must go after part one and before part three, or the result is out of order.
Testing
Results from running the reference solution:
[[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]].[[3,5]],[0,1]gives[[0, 1], [3, 5]].[[1,2],[3,4]],[2,3]gives[[1, 4]].[[1,2],[6,7]],[0,10]gives[[0, 10]].
