Problem overview
The method insert receives intervals, an Array[Array[Int]] of intervals sorted by start with no two overlapping or touching, and newInterval, an Array[Int] holding a start and an end. It returns the intervals after inserting newInterval and merging it with every interval it overlaps. The result stays sorted, with no overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5].
For [[1,3],[6,9]] and [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. With no intervals, [5,7] gives [[5,7]]. The lesson asks for O(n) time.
Approach: before, overlapping, after
Sorting everything again would cost O(n log n), and the input is already sorted, so one pass is enough. Because the intervals are sorted and don't overlap, the list splits into three consecutive parts:
- the intervals that end before the new one starts, which go into the answer unchanged;
- the intervals that overlap the new one, which all merge into a single interval;
- the intervals that start after the merged one ends, which go in unchanged.
A single index i walks through the intervals once, and each part continues where the previous one stopped. In part two, the growing interval keeps its own start and end. Every interval that overlaps it can only widen it: an earlier start or a later end.
Step by step
- Create
resultas an emptymutable.ArrayBuffer[Array[Int]], since the number of output intervals isn't known in advance. - Store the length in
val nand declarevar istarting at 0. - Part one, a
whileloop. It runs whilei < nandintervals(i)(1) < newInterval(0), that is, while intervaliends before the new one starts. Use<: an interval that ends exactly where the new one starts touches it and must merge. Checkingi < nfirst lets&&stop before it reads past the end. - Inside it, add
intervals(i)toresultwith+=and move on withi += 1. - Part two begins with two
vars,startandend, set tonewInterval(0)andnewInterval(1). They arevarbecause merging changes them. - A second
whileloop runs whilei < nandintervals(i)(0) <= end. Every remaining interval ends at or afternewInterval(0), so it overlaps the growing one exactly when it starts byend. Here<=is right, since an interval starting exactly atendtouches it. - Merge the start:
start = math.min(start, intervals(i)(0)). - Merge the end:
end = math.max(end, intervals(i)(1)). The larger value matters when an interval lies completely inside the new one. - Advance
i += 1. Without it the loop would look at the same interval forever. - Add the merged interval
Array(start, end)toresult. It goes after part one and before part three, which keeps the result sorted. If nothing overlapped, it is justnewInterval. - Part three, a third
whileloop runs whilei < n. Every interval left starts afterend, so none overlaps the merged one. - Inside it, add
intervals(i)and doi += 1, as in part one. - End with
result.toArray.
The solution in Scala
class Solution {
def insert(intervals: Array[Array[Int]], newInterval: Array[Int]): Array[Array[Int]] = {
val result = mutable.ArrayBuffer[Array[Int]]()
val n = intervals.length
var i = 0
while (i < n && intervals(i)(1) < newInterval(0)) {
result += intervals(i)
i += 1
}
var start = newInterval(0)
var end = newInterval(1)
while (i < n && intervals(i)(0) <= end) {
start = math.min(start, intervals(i)(0))
end = math.max(end, intervals(i)(1))
i += 1
}
result += Array(start, end)
while (i < n) {
result += intervals(i)
i += 1
}
result.toArray
}
}
The Scala details worth a closer look:
mutable.ArrayBuffer. It comes fromscala.collection.mutable, which the lesson's code already has in scope. In a file of your own, addimport scala.collection.mutable. AnArrayhas a fixed size, while a buffer grows with+=.valandvar.resultandnnever get reassigned, so they areval. The index and the growing interval's ends change, so they arevar. The buffer is avalwhose contents still change.whileloops. The loop parts need an index that continues from one loop to the next, which is why this solution useswhileand a sharedvar irather thanforloops with separate ranges.&&short-circuits. Ini < n && intervals(i)(1) < ..., the right side is skipped wheni < nis false, sointervals(i)is never read out of bounds.- Shared inner arrays.
result += intervals(i)adds the same inner array as the input holds, not a copy. That is fine here because the method never modifies them.
Complexity
Time: O(n). The index i only moves forward and each interval is handled once across the three loops, with constant work each time.
Space: O(n). The result holds up to n + 1 intervals. Beyond the output, only a few variables are used.
Edge cases and common mistakes
- No intervals. All three loops are skipped and the answer is just
newInterval:[], [5,7]gives[[5,7]]. - New interval before everything.
[[3,5]]with[0,1]gives[[0,1],[3,5]]. Part one is empty and the new interval is added first. - New interval after everything.
[[3,5]]with[7,9]gives[[3,5],[7,9]]. Part one takes the old interval and the new one follows. - Fits in a gap.
[[1,2],[5,6]]with[3,4]gives[[1,2],[3,4],[5,6]]. - Inside an existing interval.
[[1,5]]with[2,3]gives[[1,5]], because the larger end keeps 5. - Touching on either side.
[[1,4],[6,9]]with[4,6]gives[[1,9]], and[[3,5]]with[5,8]gives[[3,8]]. Using<=in the first loop or<in the second would leave touching intervals unmerged. - Swallowing everything.
[[1,2],[3,4]]with[0,10]gives[[0,10]]. - Forgetting
i += 1. Awhileloop without it never ends.
Testing
[[1,3],[6,9]]with[2,5]gives[[1,5],[6,9]].[[1,2],[3,5],[6,7],[8,10],[12,16]]with[4,8]gives[[1,2],[3,10],[12,16]].[]with[5,7]gives[[5,7]].[[3,5]]with[1,2]gives[[1,2],[3,5]].[[1,4],[6,9]]with[4,6]gives[[1,9]].[[1,2],[3,4]]with[0,10]gives[[0,10]].
