Skip to content

Merge Intervals

Combine overlapping ranges into one: sort by start, then extend or close the current range in one sweep.

MediumIntervals
Solve on LeetCode

The problem

You get an array of intervals, where each interval is [start, end]. Merge every group of overlapping intervals into a single interval and return the resulting intervals, which must not overlap each other and must cover exactly the same points as the input. Intervals that only touch, like [1, 3] and [3, 5], count as overlapping.

Input intervals = [[8, 10], [1, 4], [2, 6], [12, 15], [13, 14]]

Output [[1, 6], [8, 10], [12, 15]]

[1, 4] and [2, 6] overlap and become [1, 6], and [13, 14] sits inside [12, 15].

Input intervals = [[5, 7], [7, 9]]

Output [[5, 9]]

The two intervals share the point 7, so they merge.

Key constraint: The intervals arrive in no particular order, and one interval can overlap many others or sit completely inside another.

How to spot the pattern

  • Ranges that may overlap have to be combined into bigger ranges.
  • Once the intervals are sorted by start, an interval can only overlap the group just before it.

The idea

Sort the intervals by start. Then each interval either overlaps the merged interval you are building, because it starts at or before that interval's end, or it starts after it, and then no later interval can reach back to the earlier group either. So a single sweep is enough: stretch the current merged interval when the next one overlaps it, and otherwise close it and start a new one.

Brute force: Compare every interval with every other one and merge any overlapping pair, repeating until nothing changes, which takes O(n^2) time or worse.

Step by step

  1. 1Sort the intervals by their start.
  2. 2Walk through them with an empty result list.
  3. 3If the result is empty or the interval starts after the end of the last merged interval, append a copy of it as a new group.
  4. 4Otherwise set the last merged interval's end to the larger of the two ends.
  5. 5Return the result.

See the pattern move

The intervals pattern on a small example. Step through it, or press play.

Code

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        merged = []
        for start, end in sorted(intervals, key=lambda iv: iv[0]):
            if not merged or start > merged[-1][1]:
                merged.append([start, end])  # starts a new group
            else:
                merged[-1][1] = max(merged[-1][1], end)  # overlaps: stretch the group
        return merged

Complexity

Time

O(n log n)

Space

O(n)

Sorting dominates and the sweep is O(n); the output can hold up to n intervals.

Watch out for

  • Setting the merged end to the new interval's end instead of the larger of the two ends, which breaks when one interval sits inside another, like [1, 10] and [2, 3].
  • Using < instead of <= in the overlap check, which keeps touching intervals like [5, 7] and [7, 9] apart.
  • Forgetting to sort first, or sorting by end instead of by start.

Follow-up questions

What if the input is already sorted by start?

Skip the sort and the whole thing is O(n). Insert Interval is that situation with one extra interval to fit in.

What if new intervals keep arriving one at a time?

Keep the merged intervals in a balanced tree (or a sorted list) keyed by start, and merge each new interval with its neighbours there. Each insert costs O(log n) plus the number of intervals it swallows.

In Hinglish

Pehle start ke hisaab se sort karo. Phir har interval ya toh pichle group mein mil jaata hai (end badha do), ya naya group shuru karta hai.

Related problems