Start learning free

LESSON 269 OF 314 · INTERVALS

Insert Interval in TypeScript: One 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

    TYPESCRIPT · INTERVALS

    Insert Interval in TypeScript, explained

    Problem overview

    The method insert(intervals: number[][], newInterval: number[]): number[][] receives a list of [start, end] intervals that is already sorted by start with no two overlapping, plus one more interval. It returns the list after inserting newInterval, merged with every interval it overlaps, still sorted and with no overlaps. Intervals that only touch, like [1,4] and [4,5], share the point 4, so they merge into [1,5].

    For intervals = [[1,3],[6,9]] and newInterval = [2,5] the result is [[1,5],[6,9]]. For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8] the result is [[1,2],[3,10],[12,16]]: the new interval overlaps [3,5] and [6,7] and touches [8,10] at 8, so all four become [3,10]. With an empty list, the result holds only the new interval. The solution should run in O(n) time.

    Approach: three parts in one pass

    Because the list is already sorted and has no overlaps, there is no need to sort or to search. Every interval falls into exactly one of three groups, in this order:

    1. Before: intervals that end before newInterval starts. They go into the result unchanged.
    2. Overlapping: intervals that start no later than the new interval's growing end. They all merge with it into one interval.
    3. After: everything left. These start after the merged interval ends, so they also go in unchanged.

    One index i walks through the list once, and each group picks up where the previous one stopped. Sorting a combined list and merging it would also work, but it costs O(n log n). Using the existing order brings that down to O(n).

    Step by step

    1. Declare result with const, typed number[][], as an empty array.
    2. Store the length in const n = intervals.length, and declare the index i with let, starting at 0. It moves forward, so it can't be const.
    3. Part one: a while loop that runs while i < n and intervals[i][1] < newInterval[0]. Use <: an interval that ends exactly where the new one starts touches it, and touching intervals merge. Put i < n first, so && stops before reading intervals[i] when the intervals run out.
    4. Inside it, push intervals[i] onto result and do i++.
    5. Part two: keep the growing interval in two variables, start and end, declared with one let and set to newInterval[0] and newInterval[1].
    6. A second while loop runs while i < n and intervals[i][0] <= end. Every interval that is left ends at or after newInterval[0], so it overlaps exactly when it starts by end. Use <= here, because touching counts as overlap.
    7. Widen the start with Math.min(start, intervals[i][0]). Only the first overlapping interval can start earlier than the new one.
    8. Widen the end with Math.max(end, intervals[i][1]). An interval can lie completely inside the new one, like [4,5] inside [3,9], and then end must stay 9.
    9. Advance with i++. Without it the loop would repeat forever on the same interval.
    10. Push the merged interval [start, end] onto result. It belongs after the intervals of part one and before those of part three. If nothing overlapped, start and end are still the new interval's own values.
    11. Part three: a third while loop that runs while i < n.
    12. Inside it, push intervals[i] and do i++, as in part one.
    13. Return result.

    For [[1,2],[3,5],[6,7],[8,10],[12,16]] and [4,8], part one pushes [1,2] and stops with i = 1. Part two then merges as follows:

    merged with [3,5]  -> start=3 end=8
    merged with [6,7]  -> start=3 end=8
    merged with [8,10] -> start=3 end=10

    The loop stops at i = 4, because [12,16] starts after 10. The merged [3,10] is pushed, then part three adds [12,16].

    The solution in TypeScript

    class Solution {
        insert(intervals: number[][], newInterval: number[]): number[][] {
            const result: number[][] = [];
            const n = intervals.length;
            let i = 0;
            while (i < n && intervals[i][1] < newInterval[0]) {
                result.push(intervals[i]);
                i++;
            }
            let start = newInterval[0], end = newInterval[1];
            while (i < n && intervals[i][0] <= end) {
                start = Math.min(start, intervals[i][0]);
                end = Math.max(end, intervals[i][1]);
                i++;
            }
            result.push([start, end]);
            while (i < n) {
                result.push(intervals[i]);
                i++;
            }
            return result;
        }
    }
    

    The TypeScript details worth knowing:

    • One let for two variables. let start = newInterval[0], end = newInterval[1]; declares both, and both are inferred as number.
    • Short-circuit && guards the index. In i < n && intervals[i][1] < ..., the second part runs only if the first is true. Reversed, the code would read intervals[n], which is undefined, and then undefined[1] throws a TypeError at run time.
    • The input arrays are reused, not copied. result.push(intervals[i]) puts the very same inner array into the result. Changing an inner array of the result later would change the caller's input too. The merged interval is a new array, and the function never changes the input, so it is safe as written. result[0] === intervals[0] is true for an untouched interval.
    • No sorting needed, so no compare function is involved. The input's guarantees do the work.
    • Types are erased. number[] for newInterval doesn't check at run time that it has two elements.

    Complexity

    Time: O(n). The three loops share one index that only moves forward, so every interval is visited exactly once.

    Space: O(n) for the result array, which can hold all n intervals plus the new one. Beyond the output, the function uses only a few variables.

    Edge cases and common mistakes

    • Empty list. [] with [5,7] gives [[5,7]]: all three loops are skipped, and the merged interval is the new one.
    • New interval inside an existing one. [[1,5]] with [2,3] gives [[1,5]]: start drops to 1 and end rises to 5.
    • New interval after everything. [[1,5]] with [6,8] gives [[1,5],[6,8]].
    • New interval before everything. [[3,5]] with [0,1] gives [[0,1],[3,5]]. Part one pushes nothing, and part two's loop is skipped because 3 is greater than 1.
    • Touching. [[1,4]] with [4,5] gives [[1,5]]. Using <= in part one or < in part two would leave the pair split in two.
    • New interval covers everything. [[1,2],[3,4]] with [0,10] gives [[0,10]].
    • Forgetting the Math.min or Math.max. Assigning end = intervals[i][1] directly would shrink the merged interval when an existing one lies inside it.
    • Pushing the merged interval at the wrong place. The result would no longer be sorted by start.

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