Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in Rust: A Three-Part Linear Pass in O(n)

Practice O(n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. The list is sorted by start, and no two intervals overlap.

You also get one more interval, newInterval = [start, end].

Add newInterval to the list. Merge it with every interval it overlaps. Return an array of the resulting intervals, still sorted by start and with no overlaps.

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

 

Example 1:

Input: intervals = [[2,4],[7,9],[12,15]], newInterval = [8,13]
Output: [[2,4],[7,15]]
Explanation: [8,13] overlaps [7,9] and [12,15].
The three become [7,15].
[2,4] ends before 8. It stays as it is.

Example 2:

Input: intervals = [[1,2],[6,8]], newInterval = [3,5]
Output: [[1,2],[3,5],[6,8]]
Explanation: [3,5] fits in the gap between [1,2] and [6,8].
Nothing merges.

Example 3:

Input: intervals = [[0,3],[5,6]], newInterval = [3,5]
Output: [[0,6]]
Explanation: [3,5] touches [0,3] at 3.
It also touches [5,6] at 5.
All three join into one.

 

Constraints:

  • 0 to 100,000 intervals in intervals. The list can be empty.
  • Each start and end, in intervals and in newInterval, is from 0 to 1,000,000.
  • No start is greater than its end.
  • intervals is sorted by start.
  • Each interval ends before the next one starts (endi < starti+1). They don't even touch.

Note:

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

STEP 1 OF 13
    Ctrl + Enter to check

    RUST · INTERVALS

    Insert Interval in Rust, explained

    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:

    1. Those that end before the new interval starts. They go to the result unchanged.
    2. Those that overlap it. They all merge with it into one interval, with the smallest start and the largest end among them.
    3. 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

    1. Declare result as an empty Vec<Vec<i32>> with let mut.
    2. Store the length in n and create the index let mut i = 0. Since i is compared with n (a usize), Rust infers that it is a usize too.
    3. 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 check i < n comes first, so && stops before reading past the end.
    4. Copy it over: push intervals[i].clone() onto result and do i += 1.
    5. 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.
    6. Part two loop: while i < n && intervals[i][0] <= end. Every interval left ends at or after new_interval[0], so it overlaps the growing one exactly when it starts by end. Here the comparison is <=, so an interval starting exactly at end merges. Since the list is sorted, once one starts after end, all the rest do too.
    7. Widen the start: start = start.min(intervals[i][0]). Only the first overlapping interval can start earlier than the new one.
    8. 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 then end must stay 9.
    9. Advance with i += 1, or the loop would look at the same interval forever.
    10. 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, start and end are still the new interval's own.
    11. Part three: while i < n. Everything left starts after the merged interval ends.
    12. Copy them over with clone() and i += 1, as in part one.
    13. Return result as 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 of Vec<Vec<i32>>" because Vec<i32> isn't Copy. clone() makes an independent copy, and intervals keeps the original.
    • Destructuring with mut. let (mut start, mut end) = (...) marks each new variable mutable on its own.
    • min and max are methods on integers: a.min(b) and a.max(b).
    • Short-circuit &&. With i < n on the left, the right side runs only for valid indexes. Indexing outside the vector would panic.
    • Inferred types. i is a usize, which is what indexing requires, and start and end are i32 from new_interval.
    • Ownership. Both vectors are taken by value. The function only reads intervals and builds a new vector, so the clones are what make result independent 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 why min and max are 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 the min, start stays 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]].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free