Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in Rust: Sort by Start, Then One Pass in O(n log n)

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 8
    Ctrl + Enter to check

    RUST · INTERVALS

    Merge Intervals in Rust, explained

    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

    1. Sort intervals by start with sort_by_key and the closure |interval| interval[0]. It sorts in place, which is why the parameter is mut.
    2. Declare merged as an empty Vec<Vec<i32>> with let mut.
    3. 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.
    4. Name the ends with let (start, end) = (interval[0], interval[1]); so the next lines read like the idea.
    5. Start a new interval when merged is empty or merged[merged.len() - 1][1] < start, by pushing vec![start, end]. The comparison is <, not <=, because touching intervals merge.
    6. Otherwise, find the last index in else: let last = merged.len() - 1;.
    7. Extend the last interval: set merged[last][1] to merged[last][1].max(end).
    8. Return merged as 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_key takes a closure that returns the key for each element, here the start. The sort is stable and in place.
    • Short-circuit ||. When merged.is_empty() is true, the right side isn't evaluated, so merged[merged.len() - 1] never runs on an empty vector, where merged.len() - 1 would underflow a usize.
    • Why the last variable. Writing merged[merged.len() - 1][1] = ... and reading merged again on the right-hand side doesn't compile. Rust reports "cannot borrow merged as immutable because it is also borrowed as mutable", since the left side holds a mutable borrow of merged while the index expression on it reads merged.len() again. Computing the index into last first avoids the clash.
    • Owned intervals. for interval in intervals consumes the vector. Each interval is a Vec<i32>, and interval[0] copies an i32 out of it. The new interval is a fresh vec![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]]. Without max, 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]].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free