Start learning free

LESSON 551 OF 671 · INTERVALS

Insert Interval in JavaScript: One Pass in O(n) Time

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

    JAVASCRIPT · INTERVALS

    Insert Interval in JavaScript, explained

    Problem overview

    The method insert receives intervals, an array of [start, end] pairs that is already sorted by start and has no overlaps, and a newInterval. It returns the array after the new interval is inserted, merged with every interval it overlaps. The result stays sorted and free of overlaps. Intervals that only touch, like [1,4] and [4,5], count as overlapping and merge.

    Inserting [2,5] into [[1,3],[6,9]] gives [[1,5],[6,9]]. Inserting [4,8] into [[1,2],[3,5],[6,7],[8,10],[12,16]] gives [[1,2],[3,10],[12,16]], because [4,8] overlaps [3,5] and [6,7] and touches [8,10] at 8. Inserting [5,7] into an empty array gives [[5,7]]. The lesson asks for O(n) time, so no sorting is needed: the input order is already what we want.

    Approach: three parts in one pass

    Because the intervals are sorted and disjoint, they split into three groups relative to the new interval:

    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, whose start is the smallest start and whose end is the largest end among them.
    3. Intervals that start after the merged one ends. They also go in unchanged.

    A single index i walks through the array once, and each group's loop picks up where the previous one stopped. The merged interval goes in between groups one and three, so the output stays sorted.

    Step by step

    1. Declare result with const as an empty array.
    2. Store intervals.length in const n and declare the index i with let, starting at 0. It must be let because it moves forward.
    3. Part one: a while loop that runs while i < n and intervals[i][1] < newInterval[0]. Putting i < n first matters, because && then stops before it reads intervals[i] past the end. The comparison is <, since an interval ending exactly at newInterval[0] touches the new one and must merge.
    4. Inside it, push intervals[i] onto result and do i++.
    5. Part two: keep the growing interval in start and end, declared with one let and set from newInterval.
    6. A second while loop runs while i < n and intervals[i][0] <= end. Every interval left ends at or after newInterval[0], so it overlaps exactly when it starts by end. Here the comparison is <=, because an interval starting exactly at end touches the merged one.
    7. Merge the start: start = Math.min(start, intervals[i][0]).
    8. Merge the end: end = Math.max(end, intervals[i][1]). Keeping the larger end matters when an interval lies completely inside the new one.
    9. Do i++, or the loop would look at the same interval forever.
    10. After the loop, push [start, end] onto result. If nothing overlapped, these are still the new interval's own values.
    11. Part three: a third while (i < n) loop pushes the remaining intervals and advances i. All of them start after end.
    12. Return result.

    The solution in JavaScript

    class Solution {
        insert(intervals, newInterval) {
            const result = [];
            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;
        }
    }
    

    Some JavaScript details to know:

    • Short-circuit evaluation. In i < n && intervals[i][1] < ..., the right side runs only when the left side is true. Reading intervals[n] would give undefined, and indexing undefined throws a TypeError.
    • One let for two variables. let start = ..., end = ...; declares both. They are reassigned inside the loop.
    • Shared inner arrays. result.push(intervals[i]) adds the same pair object that is in the input, not a copy. In a run with [[1,2],[8,9]] and the new interval [4,5], result[0] === intervals[0] is true. The method never changes those pairs, so this is harmless, but the new pair for the merged interval is created fresh.

    Walking through the first example

    With intervals = [[1,3],[6,9]] and newInterval = [2,5], part one checks [1,3]: its end, 3, is not less than 2, so the loop stops at once and i is still 0. Part two starts with start = 2 and end = 5. Interval [1,3] starts at 1, which is at most 5, so start becomes 1 and end stays 5. Interval [6,9] starts at 6, which is more than 5, so the loop stops. The merged [1,5] is pushed, and part three pushes [6,9]. The result is [[1,5],[6,9]].

    Why not just push and merge everything?

    You could add the new interval to the array, sort it and run the merge procedure, which works but costs O(n log n). The three-part pass uses the fact that the input is already sorted and disjoint, which brings the time down to O(n).

    Complexity

    The index i only moves forward, and each interval is visited by exactly one of the three loops, so the time is O(n). The result holds up to n + 1 intervals, so the extra space is O(n).

    Edge cases and common mistakes

    • Empty input. All three loops are skipped, and the result is just [[5,7]] for the new interval [5,7].
    • No overlap, after everything. Inserting [5,6] into [[1,2],[3,4]] gives [[1,2],[3,4],[5,6]].
    • No overlap, before everything. Inserting [0,1] into [[3,4],[5,6]] gives [[0,1],[3,4],[5,6]], because part one does nothing and the merged interval is pushed first.
    • New interval inside an existing one. Inserting [2,3] into [[1,5]] gives [[1,5]]. Math.min and Math.max keep the wider bounds.
    • New interval covering everything. Inserting [1,8] into [[3,5]] gives [[1,8]].
    • Touching on both sides. Inserting [2,4] into [[1,2],[4,5]] gives [[1,5]], and [2,6] into [[1,2],[6,7]] gives [[1,7]]. Using <= in part one or < in part two would leave these touching intervals unmerged.

    Testing

    Results from the reference solution:

    [[1,3],[6,9]], [2,5]                              -> [[1,5],[6,9]]
    [[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]         -> [[1,2],[3,10],[12,16]]
    [], [5,7]                                         -> [[5,7]]
    [[1,2],[3,4]], [2,3]                              -> [[1,4]]
    
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free