Problem overview
The function insert receives intervals, a vector of intervals (each a Vec<i32> with a start and an end) that is already sorted by start with no two overlapping, and one more interval, new_interval. It returns the intervals after the insertion, merging the new one with every interval it overlaps. The result stays sorted and non-overlapping.
Intervals that only touch also merge: [1, 4] and [4, 5] become [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 at all, the result is just the new interval.
Approach: before, overlapping, after
Appending the new interval and sorting would work in O(n log n), but the input is already sorted, so one pass in O(n) is enough. Because of the order, the intervals fall into three consecutive groups relative to the new one:
- Those that end before the new interval starts. They go to the result unchanged.
- Those that overlap it. They all merge with it into one interval, with the smallest start and the largest end among them.
- Those that start after the merged interval ends. They go to the result unchanged.
One index, i, walks through the intervals once, and each group picks up where the previous one stopped.
Step by step
- Declare
resultas an emptyVec<Vec<i32>>withlet mut. - Store the length in
nand create the indexlet mut i = 0. Sinceiis compared withn(ausize), Rust infers that it is ausizetoo. - Part one:
while i < n && intervals[i][1] < new_interval[0]. An interval that ends before the new one starts needs no change. The comparison is<: an interval that ends exactly where the new one starts touches it, and touching intervals merge. The checki < ncomes first, so&&stops before reading past the end. - Copy it over: push
intervals[i].clone()ontoresultand doi += 1. - Part two setup: keep the growing interval in
let (mut start, mut end) = (new_interval[0], new_interval[1]);. Both change as intervals merge in. - Part two loop:
while i < n && intervals[i][0] <= end. Every interval left ends at or afternew_interval[0], so it overlaps the growing one exactly when it starts byend. Here the comparison is<=, so an interval starting exactly atendmerges. Since the list is sorted, once one starts afterend, all the rest do too. - Widen the start:
start = start.min(intervals[i][0]). Only the first overlapping interval can start earlier than the new one. - Widen the end:
end = end.max(intervals[i][1]). An interval can lie fully inside the growing one, such as[4, 5]inside[3, 9], and thenendmust stay 9. - Advance with
i += 1, or the loop would look at the same interval forever. - Push the merged interval
vec![start, end]. It goes after the part-one intervals and before the part-three ones, so the order stays sorted. If nothing overlapped,startandendare still the new interval's own. - Part three:
while i < n. Everything left starts after the merged interval ends. - Copy them over with
clone()andi += 1, as in part one. - Return
resultas the final expression.
The solution in Rust
impl Solution {
fn insert(intervals: Vec<Vec<i32>>, new_interval: Vec<i32>) -> Vec<Vec<i32>> {
let mut result: Vec<Vec<i32>> = Vec::new();
let n = intervals.len();
let mut i = 0;
while i < n && intervals[i][1] < new_interval[0] {
result.push(intervals[i].clone());
i += 1;
}
let (mut start, mut end) = (new_interval[0], new_interval[1]);
while i < n && intervals[i][0] <= end {
start = start.min(intervals[i][0]);
end = end.max(intervals[i][1]);
i += 1;
}
result.push(vec![start, end]);
while i < n {
result.push(intervals[i].clone());
i += 1;
}
result
}
}
The Rust details worth a closer look:
- Why
clone(). Indexing a vector can't move an element out of it.result.push(intervals[i])fails with "cannot move out of index ofVec<Vec<i32>>" becauseVec<i32>isn'tCopy.clone()makes an independent copy, andintervalskeeps the original. - Destructuring with
mut.let (mut start, mut end) = (...)marks each new variable mutable on its own. minandmaxare methods on integers:a.min(b)anda.max(b).- Short-circuit
&&. Withi < non the left, the right side runs only for valid indexes. Indexing outside the vector would panic. - Inferred types.
iis ausize, which is what indexing requires, andstartandendarei32fromnew_interval. - Ownership. Both vectors are taken by value. The function only reads
intervalsand builds a new vector, so the clones are what makeresultindependent of the input.
Complexity
Time: O(n), where n is the number of intervals. i only moves forward and each interval is looked at once across the three loops.
Space: O(n). The result holds up to n + 1 intervals, and cloning each one copies two numbers.
Edge cases and common mistakes
- Empty input.
[]with[5, 7]gives[[5, 7]]: none of the loops runs, and the merged interval is the new one. - New interval in a gap.
[[1, 2], [8, 9]]with[4, 5]gives[[1, 2], [4, 5], [8, 9]]. - New interval at either end.
[[5, 6]]with[1, 2]gives[[1, 2], [5, 6]], and[[1, 2]]with[5, 6]gives[[1, 2], [5, 6]]. - New interval inside an old one.
[[3, 9]]with[4, 5]gives[[3, 9]]. This is whyminandmaxare both needed: the start and the end of the old interval win. - Touching.
[[1, 4]]with[4, 6]gives[[1, 6]]. Using<=in the first loop would send[1, 4]to the result unchanged and give[[1, 4], [4, 6]]. - Covering everything.
[[1, 2], [3, 4]]with[0, 10]gives[[0, 10]]. - Bridging two intervals.
[[1, 2], [3, 4]]with[2, 3]gives[[1, 4]]: it touches both. - Forgetting
start.min. For[[2, 6]]with[4, 8], the merged interval must start at 2. Without themin,startstays 4 and the result is wrong.
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, 2], [8, 9]]with[4, 5]gives[[1, 2], [4, 5], [8, 9]].[[1, 4]]with[4, 6]gives[[1, 6]].[[1, 2], [3, 4]]with[2, 3]gives[[1, 4]].
