Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in C++: A Single Pass in Three Parts, O(n)

Practice O(n) Read the full explanation

You get a vector 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 a vector 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

    C++ · INTERVALS

    Insert Interval in C++, explained

    Problem overview

    The method insert receives a vector intervals of [start, end] pairs that is already sorted by start and has no overlapping or touching pairs, plus one more interval, newInterval. It inserts the new interval, merges it with every interval it overlaps, and returns the result: still sorted, still without overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge into [1,5].

    With intervals = [[1,3],[6,9]] and newInterval = [2,5] the answer is [[1,5],[6,9]]. With intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]] and newInterval = [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, the answer holds just the new one. The expected time is O(n).

    Approach: before, overlapping, after

    Because the input is sorted and free of overlaps, no sorting is needed. Every interval falls into exactly one of three groups, and the groups come in this order:

    1. Intervals that end before the new one starts. They go into the answer unchanged.
    2. Intervals that overlap the new one. They all merge with it into one interval, which only ever grows: an earlier start, a later end.
    3. Intervals that start after the merged interval ends. They also go in unchanged.

    One index i walks through intervals once. Each of three loops picks up where the previous one stopped, so the whole thing is one pass. Compared with the Merge Intervals idea of sorting everything first, this problem saves the O(n log n) sort, because the order is given.

    Step by step

    1. Declare result, a vector<vector<int>> that will hold the answer.
    2. Store the count and the index. n is intervals.size() and i starts at 0.
    3. Part one, the loop. While i < n and intervals[i][1] < newInterval[0], the interval ends before the new one begins. The check i < n comes first, so that && stops before reading past the end. The comparison is strict: an interval ending exactly at newInterval[0] touches it and must be merged.
    4. Part one, the body. push_back(intervals[i]) and increase i.
    5. Part two, the growing interval. Declare start as newInterval[0] and end as newInterval[1].
    6. Part two, the loop. While i < n and intervals[i][0] <= end, the interval starts no later than the growing one ends. Every interval that is left ends at or after newInterval[0], so this is exactly the overlap test. It uses <= because an interval starting exactly at end touches it. Since the input is sorted, once one interval starts after end, all the rest do too.
    7. Widen the start with min(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one.
    8. Widen the end with max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside the growing one, like [4,5] inside [3,9].
    9. Move on with i++, or the loop would look at the same interval forever.
    10. Push the merged interval {start, end} onto result. It goes after part one and before part three, so the order by start is kept.
    11. Part three, the loop. While i < n, every interval left starts after end, so none can overlap the merged one.
    12. Part three, the body. As in part one, push_back(intervals[i]) and i++.
    13. Return result.

    The solution in C++

    class Solution {
    public:
        vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
            vector<vector<int>> result;
            int n = intervals.size();
            int i = 0;
            while (i < n && intervals[i][1] < newInterval[0]) {
                result.push_back(intervals[i]);
                i++;
            }
            int start = newInterval[0], end = newInterval[1];
            while (i < n && intervals[i][0] <= end) {
                start = min(start, intervals[i][0]);
                end = max(end, intervals[i][1]);
                i++;
            }
            result.push_back({start, end});
            while (i < n) {
                result.push_back(intervals[i]);
                i++;
            }
            return result;
        }
    };
    

    For the second example, the first loop keeps [1,2], which ends at 2, before 4. The second loop then absorbs [3,5] (the growing interval becomes [3,8]), [6,7] (still [3,8]) and [8,10] (now [3,10]). It stops at [12,16], which starts after 10. The merged [3,10] is pushed, then the third loop keeps [12,16]. The result is [[1,2],[3,10],[12,16]].

    The C++ details:

    • int n = intervals.size() converts the unsigned size to int, so the comparisons i < n are between two signed numbers.
    • Short-circuit &&. In i < n && intervals[i][1] < ..., the right side is evaluated only when i < n holds. Reading intervals[i] with i == n is undefined behaviour in C++, not a clean error.
    • push_back(intervals[i]) copies that inner vector into result, and push_back({start, end}) builds a new one from the braces.
    • int start = newInterval[0], end = newInterval[1]; declares two variables of the same type in one statement.
    • The inputs are not changed. Unlike the sorting lessons, this function only reads intervals and newInterval and builds a new vector.

    Complexity

    Time: O(n). The index i only moves forward and the three loops together visit each interval once, with constant work each.

    Space: O(n) for result, which holds up to n + 1 intervals.

    Edge cases and common mistakes

    • No intervals. [] with [5,7] gives [[5,7]]: all three loops are skipped except the push in the middle.
    • The new interval fits between two intervals. [[1,2],[8,9]] with [4,5] gives [[1,2],[4,5],[8,9]]. The second loop never runs.
    • The new interval comes first or last. [[4,5]] with [1,2] gives [[1,2],[4,5]], and with [7,8] gives [[4,5],[7,8]].
    • The new interval bridges two intervals. [[1,2],[3,4]] with [2,3] gives [[1,4]].
    • The new interval lies inside an existing one. [[3,9]] with [4,5] gives [[3,9]]. Using max and min keeps the wider bounds.
    • Touching on the right with < instead of <= in part two. For [[1,2],[5,6]] with [3,5], the interval [5,6] touches the new one at 5. A strict comparison leaves them separate and returns [[1,2],[3,5],[5,6]] instead of merging.
    • Checking intervals[i] before i < n. This reads one element past the end once the first loop reaches the last interval.

    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,2],[3,4]] with [2,3] gives [[1,4]].
    • [[1,5]] with [0,0] gives [[0,0],[1,5]].
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free