Problem overview
The method insert receives intervals, an array of [start, end] pairs that is already sorted by start and has no overlaps, and a newInterval. It returns the array after the new interval is inserted, merged with every interval it overlaps. The result stays sorted and free of overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge.
Inserting [2,5] into [[1,3],[6,9]] gives [[1,5],[6,9]]. Inserting [4,8] into [[1,2],[3,5],[6,7],[8,10],[12,16]] gives [[1,2],[3,10],[12,16]], because [4,8] overlaps [3,5] and [6,7] and touches [8,10] at 8. Inserting [5,7] into an empty array gives [[5,7]]. The lesson asks for O(n) time, so no sorting is needed: the input order is already what we want.
Approach: three parts in one pass
Because the intervals are sorted and disjoint, they split into three groups relative to the new interval:
- Intervals that end before the new one starts. They go into the answer unchanged.
- Intervals that overlap the new one. They all merge with it into one interval, whose start is the smallest start and whose end is the largest end among them.
- Intervals that start after the merged one ends. They also go in unchanged.
A single index i walks through the array once, and each group's loop picks up where the previous one stopped. The merged interval goes in between groups one and three, so the output stays sorted.
Step by step
- Declare
resultwithconstas an empty array. - Store
intervals.lengthinconst nand declare the indexiwithlet, starting at 0. It must beletbecause it moves forward. - Part one: a
whileloop that runs whilei < nandintervals[i][1] < newInterval[0]. Puttingi < nfirst matters, because&&then stops before it readsintervals[i]past the end. The comparison is<, since an interval ending exactly atnewInterval[0]touches the new one and must merge. - Inside it, push
intervals[i]ontoresultand doi++. - Part two: keep the growing interval in
startandend, declared with oneletand set fromnewInterval. - A second
whileloop runs whilei < nandintervals[i][0] <= end. Every interval left ends at or afternewInterval[0], so it overlaps exactly when it starts byend. Here the comparison is<=, because an interval starting exactly atendtouches the merged one. - Merge the start:
start = Math.min(start, intervals[i][0]). - Merge the end:
end = Math.max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside the new one. - Do
i++, or the loop would look at the same interval forever. - After the loop, push
[start, end]ontoresult. If nothing overlapped, these are still the new interval's own values. - Part three: a third
while (i < n)loop pushes the remaining intervals and advancesi. All of them start afterend. - Return
result.
The solution in JavaScript
class Solution {
insert(intervals, newInterval) {
const result = [];
const n = intervals.length;
let i = 0;
while (i < n && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
let start = newInterval[0], 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++;
}
result.push([start, end]);
while (i < n) {
result.push(intervals[i]);
i++;
}
return result;
}
}
Some JavaScript details to know:
- Short-circuit evaluation. In
i < n && intervals[i][1] < ..., the right side runs only when the left side is true. Readingintervals[n]would giveundefined, and indexingundefinedthrows aTypeError. - One
letfor two variables.let start = ..., end = ...;declares both. They are reassigned inside the loop. - Shared inner arrays.
result.push(intervals[i])adds the same pair object that is in the input, not a copy. In a run with[[1,2],[8,9]]and the new interval[4,5],result[0] === intervals[0]istrue. The method never changes those pairs, so this is harmless, but the new pair for the merged interval is created fresh.
Walking through the first example
With intervals = [[1,3],[6,9]] and newInterval = [2,5], part one checks [1,3]: its end, 3, is not less than 2, so the loop stops at once and i is still 0. Part two starts with start = 2 and end = 5. Interval [1,3] starts at 1, which is at most 5, so start becomes 1 and end stays 5. Interval [6,9] starts at 6, which is more than 5, so the loop stops. The merged [1,5] is pushed, and part three pushes [6,9]. The result is [[1,5],[6,9]].
Why not just push and merge everything?
You could add the new interval to the array, sort it and run the merge procedure, which works but costs O(n log n). The three-part pass uses the fact that the input is already sorted and disjoint, which brings the time down to O(n).
Complexity
The index i only moves forward, and each interval is visited by exactly one of the three loops, so the time is O(n). The result holds up to n + 1 intervals, so the extra space is O(n).
Edge cases and common mistakes
- Empty input. All three loops are skipped, and the result is just
[[5,7]]for the new interval[5,7]. - No overlap, after everything. Inserting
[5,6]into[[1,2],[3,4]]gives[[1,2],[3,4],[5,6]]. - No overlap, before everything. Inserting
[0,1]into[[3,4],[5,6]]gives[[0,1],[3,4],[5,6]], because part one does nothing and the merged interval is pushed first. - New interval inside an existing one. Inserting
[2,3]into[[1,5]]gives[[1,5]].Math.minandMath.maxkeep the wider bounds. - New interval covering everything. Inserting
[1,8]into[[3,5]]gives[[1,8]]. - Touching on both sides. Inserting
[2,4]into[[1,2],[4,5]]gives[[1,5]], and[2,6]into[[1,2],[6,7]]gives[[1,7]]. Using<=in part one or<in part two would leave these touching intervals unmerged.
Testing
Results from the reference solution:
[[1,3],[6,9]], [2,5] -> [[1,5],[6,9]]
[[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8] -> [[1,2],[3,10],[12,16]]
[], [5,7] -> [[5,7]]
[[1,2],[3,4]], [2,3] -> [[1,4]]
