Start learning free

LESSON 550 OF 671 · INTERVALS

Merge Intervals in JavaScript: 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

    JAVASCRIPT · INTERVALS

    Merge Intervals in JavaScript, explained

    Problem overview

    The method merge receives intervals, an array of [start, end] pairs in any order. It combines every group of overlapping intervals into one and returns the result 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 answer is [[1,6],[8,10],[15,18]]: the first two overlap and the others stand alone. For [[6,8],[1,9],[2,4],[4,7]] the input isn't sorted, and [1,9] covers all the others, so the answer is [[1,9]]. The lesson asks for O(n log n) time.

    Approach: sort by start, then extend the last interval

    Comparing every interval with every other one would be O(n²). Sorting by start removes the need: after it, intervals that overlap sit next to each other, so a single left-to-right pass can build the answer.

    Keep a list merged. For each interval in order, look at the last interval in merged, the one still growing:

    • If the current interval starts after that one ends, nothing so far can overlap it, so it begins a new merged interval.
    • Otherwise it overlaps (or touches) the last one, so extend the last one's end to cover it.

    The extension uses the larger of the two ends, not simply the new end, because an interval can lie completely inside the last merged one. Merging [2,3] into [1,10] must leave the end at 10.

    Step by step

    1. Sort intervals by start with a compare function (first, second) => first[0] - second[0]. The negative result puts the smaller start first.
    2. Declare merged with const as an empty array. Its last element is always the interval that may still grow.
    3. Loop with for...of, destructuring each interval into [start, end], so the body doesn't need [0] and [1].
    4. Check whether a new merged interval begins: merged.length === 0 or the last merged end is less than start. Then push a new array [start, end]. Use < here and not <=, since an interval that starts exactly where the last one ends touches it and has to merge.
    5. Otherwise, in the else branch, set the end of the last merged interval to Math.max of its own end and end.
    6. Return merged. Every interval went into one of them, and they are in order of start.

    The solution in JavaScript

    class Solution {
        merge(intervals) {
            intervals.sort((first, second) => first[0] - second[0]);
            const merged = [];
            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;
        }
    }
    

    Some JavaScript details matter here:

    • The compare function is required. sort() with no argument compares elements as strings, which would put [10,12] before [2,4]. It also sorts in place, so the caller's intervals array ends up reordered.
    • Destructuring in for...of. const [start, end] = interval copies the two numbers out of each pair.
    • Pushing a new array. merged.push([start, end]) creates a fresh pair, so extending merged's last interval later doesn't change the arrays in intervals. For [[1,3],[2,6]], the input still holds [[1,3],[2,6]] after the call, even if the returned [1,6] is edited afterwards.
    • The last element. merged[merged.length - 1] is the last item. Reading it when merged is empty would give undefined, and indexing into that throws a TypeError, which is why the merged.length === 0 test comes first. The || stops as soon as it is true.

    Why only the last merged interval matters

    Because the intervals are sorted by start, every later interval starts at or after the current one. If it doesn't reach the last merged interval, it can't reach any earlier one, since those end even sooner than the last one begins. That is why one comparison per interval is enough, and why the pass never looks back.

    Walking through the first example

    For [[1,3],[2,6],[8,10],[15,18]] the input is already sorted. [1,3] goes into merged because the list is empty. [2,6] starts at 2, which is not after the last end (3), so the last interval's end becomes Math.max(3, 6), which is 6. [8,10] starts after 6, so it is pushed, and so is [15,18]. The result is [[1,6],[8,10],[15,18]].

    The merged intervals in merged are disjoint and ordered: each new one begins strictly after the previous one ends. So the array is already sorted by start when the loop finishes, and nothing needs sorting a second time. Equal starts cause no trouble either: when two intervals start at the same point, the compare function returns 0, and either order produces the same merged result.

    Complexity

    Sorting is O(n log n) and the pass is O(n), so the time is O(n log n). The merged array holds up to n intervals, so the extra space is O(n), plus whatever the sort uses internally.

    Edge cases and common mistakes

    • One interval. [[5,6]] returns [[5,6]].
    • Touching intervals. [[1,4],[4,5]] must give [[1,5]]. With <= in the new-interval test, the result is [[1,4],[4,5]].
    • An interval inside another. [[1,10],[2,3]] gives [[1,10]]. Setting the end to end without Math.max would give [[1,3]].
    • Unsorted input. [[1,4],[0,4]] gives [[0,4]] only because of the sort.
    • A late interval that bridges many. [[2,3],[4,5],[6,7],[8,9],[1,10]] sorts [1,10] to the front, and everything merges into [[1,10]].

    Testing

    Results from the reference solution:

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