Insert Interval

Pattern: Intervals

medium

The list is already sorted and separate, so one walk in three phases does it. Copy the intervals that end before the new one, grow the new one through every interval it overlaps, then copy the rest.

The problem

You are given a list of intervals [start, end] that are sorted by start and do not overlap, and one new interval. Insert the new interval so the list is still sorted and has no overlaps, merging where needed. Intervals that share an end point, such as [1, 5] and [5, 7], count as overlapping. For example, [[1, 3], [6, 9]] with [2, 5] gives [[1, 5], [6, 9]].

The function name insert matches LeetCode. Use the link above for the exact statement and limits. Return a new list. You do not have to change the input in place.

Think first

  • Which intervals can never touch the new one, and where do they sit in the list?
  • When an interval overlaps the new one, what do the two become together?
  • Once an interval starts after the new one ends, can anything later overlap it?

Hints

    Brute force, and why it fails

    Add the new interval to the list, sort again and run Merge Intervals: O(n log n). The list is already sorted, so a single walk is enough and costs O(n).

    The key insight

    Sorted, separate intervals split into three runs around the new one: before it, overlapping it, after it. Each run is one plain loop.

    Dry run

    [1, 2]0i
    [3, 5]1 
    [6, 7]2 
    [8, 10]3 
    [12, 16]4 
    new[4, 8]
    out

    intervals are [1, 2], [3, 5], [6, 7], [8, 10] and [12, 16]. The new interval is [4, 8].

    Step 1 of 4

    The plan

    out = empty list, i = 0
    [s, e] = newInterval
    while i < n and intervals[i].end < s:
        add intervals[i] to out; i = i + 1
    while i < n and intervals[i].start <= e:
        s = min(s, intervals[i].start)
        e = max(e, intervals[i].end)
        i = i + 1
    add [s, e] to out
    while i < n:
        add intervals[i] to out; i = i + 1
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each interval is looked at once. The output list holds up to n + 1 intervals.

    Edge cases

    • Empty list: the answer is just the new interval.
    • New interval inside one interval, as in [[1, 5]] with [2, 3]: [[1, 5]].
    • New interval in a gap, before everything, or after everything: nothing merges, it just goes in its place.
    • New interval joining two, as in [[1, 2], [5, 6]] with [2, 5]: [[1, 6]].
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[][] insert(int[][] intervals, int[] newInterval) {
            List<int[]> out = new ArrayList<>();
            int i = 0, n = intervals.length;
            int start = newInterval[0], end = newInterval[1];
            while (i < n && intervals[i][1] < start) out.add(intervals[i++]);   // ends before the new one starts
            while (i < n && intervals[i][0] <= end) {                           // overlaps: grow the new interval
                start = Math.min(start, intervals[i][0]);
                end = Math.max(end, intervals[i][1]);
                i++;
            }
            out.add(new int[]{start, end});
            while (i < n) out.add(intervals[i++]);                              // starts after the new one ends
            return out.toArray(new int[0][]);
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
            vector<vector<int>> out;
            size_t i = 0, n = intervals.size();
            int start = newInterval[0], end = newInterval[1];
            while (i < n && intervals[i][1] < start) out.push_back(intervals[i++]);   // ends before the new one
            while (i < n && intervals[i][0] <= end) {                                 // overlaps: grow it
                start = min(start, intervals[i][0]);
                end = max(end, intervals[i][1]);
                i++;
            }
            out.push_back({start, end});
            while (i < n) out.push_back(intervals[i++]);                              // starts after it ends
            return out;
        }
    };

    Python

    class Solution:
        def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:
            out, i, n = [], 0, len(intervals)
            start, end = newInterval
            while i < n and intervals[i][1] < start:          # ends before the new one starts
                out.append(intervals[i])
                i += 1
            while i < n and intervals[i][0] <= end:           # overlaps: grow the new interval
                start = min(start, intervals[i][0])
                end = max(end, intervals[i][1])
                i += 1
            out.append([start, end])
            out.extend(intervals[i:])                         # starts after the new one ends
            return out

    Common mistakes

    • Using ≤ in phase 1, so [1, 2] is copied unchanged when the new interval starts at 2 and should merge with it.
    • Forgetting to take the smaller start, so [3, 5] merged with [4, 8] loses the 3.
    • Forgetting to add the new interval when no interval overlaps it.

    Similar problems