Problem overview
The function merge receives intervals, a vector where each interval is a Vec<i32> holding a start and an end. It merges every group of overlapping intervals and returns what remains, sorted by start.
Two intervals overlap when they share at least one point, so intervals that only touch also merge: [1, 4] and [4, 5] become [1, 5]. For [[1, 3], [2, 6], [8, 10], [15, 18]] the result is [[1, 6], [8, 10], [15, 18]]. The input isn't sorted: [[6, 8], [1, 9], [2, 4], [4, 7]] merges into the single interval [[1, 9]].
Approach: sort first, then grow the last interval
Comparing every interval with every other is O(n²). Sorting by start fixes the order so that overlapping intervals sit next to each other, and then one pass is enough.
Keep a vector merged. Its last interval is the one still growing. For each interval, in order of start:
- If the last merged interval ends before this one starts, they can't overlap, and nothing later can overlap the earlier ones either, because later starts are even larger. Start a new merged interval.
- Otherwise they overlap, so extend the last merged interval's end to the larger of the two ends. The larger end matters when an interval lies fully inside the last one, such as
[2, 3]inside[1, 10].
Sorting costs O(n log n) and the pass costs O(n), so sorting dominates.
Here is the pass on [[6, 8], [1, 9], [2, 4], [4, 7], [11, 12]]. After sorting the order is [[1, 9], [2, 4], [4, 7], [6, 8], [11, 12]], and merged evolves like this:
after [1, 9]: [[1, 9]]
after [2, 4]: [[1, 9]]
after [4, 7]: [[1, 9]]
after [6, 8]: [[1, 9]]
after [11, 12]: [[1, 9], [11, 12]]
The first interval starts the list. The next three start at or before 9, so they overlap it, and since none ends after 9 the end stays put. Only [11, 12] starts after 9 and begins a new merged interval.
Why is it enough to compare with the last merged interval only? After sorting, every earlier interval starts no later than the current one. The last merged interval already contains all the earlier ones that overlapped it, and any merged interval before it ended before the last one began. So if the current interval doesn't reach the last merged one, it can't reach any of the earlier ones either.
Step by step
- Sort
intervalsby start withsort_by_keyand the closure|interval| interval[0]. It sorts in place, which is why the parameter ismut. - Declare
mergedas an emptyVec<Vec<i32>>withlet mut. - Loop over the intervals with
for interval in intervals. Looping over the vector itself moves each interval out in turn; the vector isn't needed afterwards. - Name the ends with
let (start, end) = (interval[0], interval[1]);so the next lines read like the idea. - Start a new interval when
mergedis empty ormerged[merged.len() - 1][1] < start, by pushingvec![start, end]. The comparison is<, not<=, because touching intervals merge. - Otherwise, find the last index in
else:let last = merged.len() - 1;. - Extend the last interval: set
merged[last][1]tomerged[last][1].max(end). - Return
mergedas the final expression.
The solution in Rust
impl Solution {
fn merge(mut intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
intervals.sort_by_key(|interval| interval[0]);
let mut merged: Vec<Vec<i32>> = Vec::new();
for interval in intervals {
let (start, end) = (interval[0], interval[1]);
if merged.is_empty() || merged[merged.len() - 1][1] < start {
merged.push(vec![start, end]);
} else {
let last = merged.len() - 1;
merged[last][1] = merged[last][1].max(end);
}
}
merged
}
}
The Rust details worth a closer look:
sort_by_keytakes a closure that returns the key for each element, here the start. The sort is stable and in place.- Short-circuit
||. Whenmerged.is_empty()is true, the right side isn't evaluated, somerged[merged.len() - 1]never runs on an empty vector, wheremerged.len() - 1would underflow ausize. - Why the
lastvariable. Writingmerged[merged.len() - 1][1] = ...and readingmergedagain on the right-hand side doesn't compile. Rust reports "cannot borrowmergedas immutable because it is also borrowed as mutable", since the left side holds a mutable borrow ofmergedwhile the index expression on it readsmerged.len()again. Computing the index intolastfirst avoids the clash. - Owned intervals.
for interval in intervalsconsumes the vector. Eachintervalis aVec<i32>, andinterval[0]copies ani32out of it. The new interval is a freshvec![start, end]. - Tuple destructuring.
let (start, end) = (a, b);declares two variables at once.
Complexity
Time: O(n log n), where n is the number of intervals. The sort takes O(n log n) and the loop takes O(n).
Space: O(n). In the worst case no intervals overlap, and merged holds n intervals. The sort happens in place.
Edge cases and common mistakes
- Touching intervals.
[[1, 4], [4, 5]]gives[[1, 5]]. With<=in the test, the result would be[[1, 4], [4, 5]]. - Nested intervals.
[[1, 10], [2, 3]]gives[[1, 10]]. Withoutmax, setting the end to 3 would shrink the interval to[1, 3]. - Skipping the sort. On
[[6, 8], [1, 9], [2, 4], [4, 7]], the same loop without the sort returns[[6, 9]], which is wrong: the start 1 is lost. - Unsorted input.
[[2, 3], [1, 10]]gives[[1, 10]]only because of the sort. - Comparing with the wrong end. The test must use the end of the last merged interval, not the end of the previous input interval. After
[1, 9]absorbs[2, 4], the later intervals must be compared against 9, not against 4. - One interval.
[[3, 4]]returns[[3, 4]]. - Single points.
[[5, 5], [5, 5]]gives[[5, 5]]: an interval may have equal start and end. - Disjoint intervals.
[[1, 2], [3, 4]]stays as it is, because 2 < 3.
Testing
[[1, 3], [2, 6], [8, 10], [15, 18]]gives[[1, 6], [8, 10], [15, 18]].[[1, 4], [4, 5]]gives[[1, 5]].[[6, 8], [1, 9], [2, 4], [4, 7]]gives[[1, 9]].[[3, 4]]gives[[3, 4]].[[1, 10], [2, 3]]gives[[1, 10]].[[1, 2], [3, 4]]gives[[1, 2], [3, 4]].
