Start learning free

LESSON 268 OF 314 · INTERVALS

Merge Intervals in TypeScript: Sort and Sweep in O(n log n)

Practice O(n log n) Read the full explanation

You get an array of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return an array of the intervals you end up with, sorted by start.

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

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

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

STEP 1 OF 6
    Ctrl + Enter to check

    TYPESCRIPT · INTERVALS

    Merge Intervals in TypeScript, explained

    Problem overview

    The method merge(intervals: number[][]): number[][] receives intervals as [start, end] pairs, merges the ones that overlap, and returns what remains, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1,4] and [4,5], merge into [1,5].

    For [[1,3],[2,6],[8,10],[15,18]] the result is [[1,6],[8,10],[15,18]]: the first two overlap and become [1,6]. For the unsorted input [[6,8],[1,9],[2,4],[4,7]] the result is [[1,9]], because [1,9] covers all the others. The solution should run in O(n log n) time.

    Approach: sort by start, then extend the last interval

    Checking every interval against every other takes O(n²). Sorting by start makes the overlapping intervals come one after another, so a single pass is enough.

    Keep a list merged of the results so far. Its last interval is the one that may still grow. For each interval in sorted order:

    • If merged is empty, or the last merged interval ends before this interval starts, there is a gap. Nothing earlier can reach this interval either, since the intervals come sorted by start. Start a new merged interval.
    • Otherwise the two overlap. Extend the last merged interval so it ends at the larger of the two ends.

    The larger end matters because an interval can lie completely inside the last merged one, like [2,3] inside [1,10]. Then the merged end must stay 10, not drop to 3.

    Step by step

    1. Sort by start with sort((first, second) => first[0] - second[0]). The sort is the slowest part, O(n log n); the merging is one pass.
    2. Declare merged with const, typed number[][], as an empty array. const is fine, because the array is changed, not replaced.
    3. Loop with for...of over intervals, destructuring each one into [start, end]. The body then never needs [0] or [1] on the current interval.
    4. Test for a gap. The condition is merged.length === 0 || merged[merged.length - 1][1] < start. If it holds, push a new array [start, end]. Use <, not <=, so touching intervals merge.
    5. Otherwise extend. In the else branch, set the end of the last merged interval to Math.max of its current end and end.
    6. Return merged. Every interval went into a merged one, in order of start.

    Here is the sweep for [[6,8],[1,9],[2,4],[4,7]]. After sorting the input is [[1,9],[2,4],[4,7],[6,8]], and merged evolves like this:

    [1,9] [[1,9]]
    [2,4] [[1,9]]
    [4,7] [[1,9]]
    [6,8] [[1,9]]

    The first interval starts the list. Each later one starts at or before the current end, 9, and ends at or before it, so the merged end stays 9.

    The solution in TypeScript

    class Solution {
        merge(intervals: number[][]): number[][] {
            intervals.sort((first, second) => first[0] - second[0]);
            const merged: number[][] = [];
            for (const [start, end] of intervals) {
                if (merged.length === 0 || merged[merged.length - 1][1] < start) {
                    merged.push([start, end]);
                } else {
                    merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], end);
                }
            }
            return merged;
        }
    }
    

    The TypeScript details worth knowing:

    • Destructuring in for...of. for (const [start, end] of intervals) unpacks each two-element array into two const variables. The compiler types them as number from number[][].
    • Pushing a new array. merged.push([start, end]) creates a fresh array rather than reusing the input one. That matters because the next lines change merged[merged.length - 1][1] in place: if the input array itself had been pushed, the caller's data would change. With the fresh copy, the input's inner arrays stay as they were, and for [[1,3],[2,6]] the first inner array is still the same object, still holding [1,3].
    • The outer array is changed. sort works in place, so the caller's intervals ends up sorted. After merge([[3,4],[1,2]]), the input reads [[1,2],[3,4]]. Sort a copy with [...intervals].sort(...) if that matters.
    • The compare function is required. A bare sort() compares the intervals as text, so [100,101] would come before [9,10].
    • Types are erased. number[][] checks nothing at run time.

    Complexity

    Time: O(n log n), where n is the number of intervals: the sort costs O(n log n) and the sweep O(n).

    Space: O(n) for the merged list, which holds up to n intervals when none overlap, plus whatever the sort uses internally.

    Edge cases and common mistakes

    • Touching intervals. [[1,4],[4,5]] gives [[1,5]]. A <= in the gap test would split them.
    • One interval inside another. [[1,10],[2,3]] gives [[1,10]]. Setting the end to the current interval's end instead of using Math.max would shrink it to 3.
    • Unsorted input. [[2,3],[1,10]] gives [[1,10]]. Without the sort, the sweep starts with [2,3] and then extends it to [2,10], losing the earlier start 1.
    • A single interval. [[5,5]] gives [[5,5]], since a zero-length interval is allowed.
    • Same start. [[1,4],[0,4]] gives [[0,4]].
    • No overlaps at all. [[1,4],[5,6]] comes back unchanged.
    • Sorting without a compare function. It sorts as text and gives a wrong order for numbers of different lengths.

    Testing

    • [[1,3],[2,6],[8,10],[15,18]] gives [[1,6],[8,10],[15,18]].
    • [[1,4],[4,5]] gives [[1,5]].
    • [[6,8],[1,9],[2,4],[4,7]] gives [[1,9]].
    • [[1,10],[2,3]] gives [[1,10]].
    • [[1,4],[5,6]] gives [[1,4],[5,6]].
    • [[5,5]] gives [[5,5]].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free