Problem overview
The method insert(intervals: number[][], newInterval: number[]): number[][] receives a list of [start, end] intervals that is already sorted by start with no two overlapping, plus one more interval. It returns the list after inserting newInterval, merged with every interval it overlaps, 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 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] the result 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 become [3,10]. With an empty list, the result holds only the new interval. The solution should run in O(n) time.
Approach: three parts in one pass
Because the list is already sorted and has no overlaps, there is no need to sort or to search. Every interval falls into exactly one of three groups, in this order:
- Before: intervals that end before
newIntervalstarts. They go into the result unchanged. - Overlapping: intervals that start no later than the new interval's growing end. They all merge with it into one interval.
- After: everything left. These start after the merged interval ends, so they also go in unchanged.
One index i walks through the list once, and each group picks up where the previous one stopped. Sorting a combined list and merging it would also work, but it costs O(n log n). Using the existing order brings that down to O(n).
Step by step
- Declare
resultwithconst, typednumber[][], as an empty array. - Store the length in
const n = intervals.length, and declare the indexiwithlet, starting at 0. It moves forward, so it can't beconst. - Part one: a
whileloop that runs whilei < nandintervals[i][1] < newInterval[0]. Use<: an interval that ends exactly where the new one starts touches it, and touching intervals merge. Puti < nfirst, so&&stops before readingintervals[i]when the intervals run out. - Inside it, push
intervals[i]ontoresultand doi++. - Part two: keep the growing interval in two variables,
startandend, declared with oneletand set tonewInterval[0]andnewInterval[1]. - A second
whileloop runs whilei < nandintervals[i][0] <= end. Every interval that is left ends at or afternewInterval[0], so it overlaps exactly when it starts byend. Use<=here, because touching counts as overlap. - Widen the start with
Math.min(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one. - Widen the end with
Math.max(end, intervals[i][1]). An interval can lie completely inside the new one, like[4,5]inside[3,9], and thenendmust stay 9. - Advance with
i++. Without it the loop would repeat forever on the same interval. - Push the merged interval
[start, end]ontoresult. It belongs after the intervals of part one and before those of part three. If nothing overlapped,startandendare still the new interval's own values. - Part three: a third
whileloop that runs whilei < n. - Inside it, push
intervals[i]and doi++, as in part one. - Return
result.
For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], part one pushes [1,2] and stops with i = 1. Part two then merges as follows:
merged with [3,5] -> start=3 end=8
merged with [6,7] -> start=3 end=8
merged with [8,10] -> start=3 end=10
The loop stops at i = 4, because [12,16] starts after 10. The merged [3,10] is pushed, then part three adds [12,16].
The solution in TypeScript
class Solution {
insert(intervals: number[][], newInterval: number[]): number[][] {
const result: number[][] = [];
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;
}
}
The TypeScript details worth knowing:
- One
letfor two variables.let start = newInterval[0], end = newInterval[1];declares both, and both are inferred asnumber. - Short-circuit
&&guards the index. Ini < n && intervals[i][1] < ..., the second part runs only if the first is true. Reversed, the code would readintervals[n], which isundefined, and thenundefined[1]throws aTypeErrorat run time. - The input arrays are reused, not copied.
result.push(intervals[i])puts the very same inner array into the result. Changing an inner array of the result later would change the caller's input too. The merged interval is a new array, and the function never changes the input, so it is safe as written.result[0] === intervals[0]istruefor an untouched interval. - No sorting needed, so no compare function is involved. The input's guarantees do the work.
- Types are erased.
number[]fornewIntervaldoesn't check at run time that it has two elements.
Complexity
Time: O(n). The three loops share one index that only moves forward, so every interval is visited exactly once.
Space: O(n) for the result array, which can hold all n intervals plus the new one. Beyond the output, the function uses only a few variables.
Edge cases and common mistakes
- Empty list.
[]with[5,7]gives[[5,7]]: all three loops are skipped, and the merged interval is the new one. - New interval inside an existing one.
[[1,5]]with[2,3]gives[[1,5]]:startdrops to 1 andendrises to 5. - New interval after everything.
[[1,5]]with[6,8]gives[[1,5],[6,8]]. - New interval before everything.
[[3,5]]with[0,1]gives[[0,1],[3,5]]. Part one pushes nothing, and part two's loop is skipped because 3 is greater than 1. - Touching.
[[1,4]]with[4,5]gives[[1,5]]. Using<=in part one or<in part two would leave the pair split in two. - New interval covers everything.
[[1,2],[3,4]]with[0,10]gives[[0,10]]. - Forgetting the
Math.minorMath.max. Assigningend = intervals[i][1]directly would shrink the merged interval when an existing one lies inside it. - Pushing the merged interval at the wrong place. The result would no longer be sorted by start.
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]].[[1,5]]with[6,8]gives[[1,5],[6,8]].[[3,5]]with[0,1]gives[[0,1],[3,5]].[[1,4]]with[4,5]gives[[1,5]].[[1,2],[3,4]]with[0,10]gives[[0,10]].
