Skip to main content
65

Merge Intervals

Mediumintervalssorting

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:IntervalsRead the beginner guide

Given an array of intervals, where intervals[i] = [start, end], merge all overlapping intervals and return the non-overlapping intervals that cover exactly the same ranges. The result may be in any order.

Understand the problem

  • An interval [start, end] is a range of numbers from start to end.
  • Merging overlapping intervals means replacing them with one interval that covers all of them: [1, 3] and [2, 6] become [1, 6].
  • For this problem, intervals that touch (like [1, 4] and [4, 5]) are merged too.
  • The input is not sorted.

Example 1

text
Input:  intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]

[1, 3] and [2, 6] overlap, so they become [1, 6]. The others don't touch anything.

Example 2

text
Input:  intervals = [[1, 4], [4, 5]]
Output: [[1, 5]]

They touch at 4, so they merge.

Example 3

text
Input:  intervals = [[1, 10], [2, 3]]
Output: [[1, 10]]

[2, 3] is completely inside [1, 10].

Constraints

  • 1 <= intervals.length <= 10^4
  • 0 <= start <= end <= 10^4

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Sort the intervals by start, then walk through them, either stretching the last merged interval to cover the next one (if they overlap) or starting a new one.

    The naive approach (and why it's slow)

    Repeatedly look for any two intervals that overlap, merge them, and start over, until no pair overlaps. Each search compares every pair: O(n²) per round, and there can be many rounds.

    The key insight: sort by start

    Once the intervals are sorted by start, every interval that overlaps the current group must come right after it in the list. There's no need to look back or far ahead.

    Walk through the sorted list, treating the last interval in the result as the current group:

    • The next interval starts at or before the group's end (start <= groupEnd): it overlaps (or touches). Extend the group: groupEnd = max(groupEnd, end).
    • Otherwise there's a gap: this interval starts a new group. Append it to the result.

    Step by step

    intervals = [[1, 3], [2, 6], [8, 10], [15, 18]] (already sorted by start):

    text
    number line:  1   2   3   4   5   6   7   8   9   10  ...  15  16  17  18
                 [1-------3]
                     [2-------------------6]
                                             [8-------10]
                                                              [15----------18]
    merged:      [1-----------------------6] [8-------10]     [15----------18]
    IntervalGroup so farStarts at or before its end?ActionResult
    [1, 3](none)start a group[1, 3]
    [2, 6][1, 3]2 <= 3: yesend = max(3, 6)[1, 6]
    [8, 10][1, 6]8 <= 6: nonew group[1, 6], [8, 10]
    [15, 18][8, 10]15 <= 10: nonew group[1, 6], [8, 10], [15, 18]

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n log n) for the sort. The sweep is O(n).
    • Memory: O(n) for the sorted copy and the result.

    Common mistakes

    • Not sorting first. Then overlapping intervals might not be next to each other.
    • Setting the end to the new interval's end instead of the max. [1, 10] then [2, 3] would wrongly become [1, 3].
    • Using < instead of <=. Then touching intervals like [1, 4] and [4, 5] wouldn't merge, which this problem requires.

    Going deeper

    • If the list is already sorted, as in Insert Interval, you can skip the sort and do it in O(n).
    • "Sort by start, then sweep and compare with the last group" solves many interval problems. It's worth knowing by heart.

    Reference solution

    js
    /**
     * @param {number[][]} intervals
     * @return {number[][]}
     */
    export default function merge(intervals) {
      // Sorted by start, anything that overlaps the current group comes right after it.
      const sorted = [...intervals].sort((a, b) => a[0] - b[0])
      const result = []
      for (const [start, end] of sorted) {
        const last = result.at(-1) // the current group (undefined before the first one)
        // Starts at or before the group's end: it overlaps (or touches), so stretch the group.
        // max, because an interval inside the group (like [2, 3] in [1, 10]) mustn't shrink it.
        if (last && start <= last[1]) last[1] = Math.max(last[1], end)
        else result.push([start, end]) // a gap: start a new group
      }
      return result
    }
    ts
    export default function merge(intervals: number[][]): number[][] {
      // Sorted by start, anything that overlaps the current group comes right after it.
      const sorted = [...intervals].sort((a, b) => a[0] - b[0])
      const result: number[][] = []
      for (const [start, end] of sorted) {
        const last = result.at(-1) // the current group (undefined before the first one)
        // Starts at or before the group's end: it overlaps (or touches), so stretch the group.
        // max, because an interval inside the group (like [2, 3] in [1, 10]) mustn't shrink it.
        if (last && start <= last[1]) last[1] = Math.max(last[1], end)
        else result.push([start, end]) // a gap: start a new group
      }
      return result
    }
    python
    def merge(intervals: list[list[int]]) -> list[list[int]]:
        result = []
        # Sorted by start, anything that overlaps the current group comes right after it.
        for start, end in sorted(intervals):
            # Starts at or before the group's end: it overlaps (or touches), so stretch the group.
            # max, because an interval inside the group (like [2, 3] in [1, 10]) mustn't shrink it.
            if result and start <= result[-1][1]:
                result[-1][1] = max(result[-1][1], end)
            else:
                result.append([start, end])  # a gap: start a new group
        return result