LeetCode #56 Medium

Merge Intervals

Merge Intervals is LeetCode 56 (Medium). You get an array intervals, where each [start, end] is a closed range of numbers.

  • Merge every group of overlapping intervals into one interval.
  • Return the intervals that are left. They must not overlap, and together they must cover exactly the same points as the input.
  • Two intervals overlap when they share at least one point, so an interval that starts exactly where another ends joins it.

The input is not sorted, and the answer may be returned in any order.

Constraints
  • 1 <= intervals.length <= 10⁴
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10⁴
arraysortingintervals
Open on LeetCode ↗
02

Intuition

Once you sort the intervals by start, every interval that can join the block you are building comes right after it, so one left-to-right pass is enough.

  • Overlap test: the next interval joins the block when its start is no later than the block's end.
  • Grow with the larger end: an interval can sit entirely inside the block, so the block's new end is the bigger of the two ends.
  • A closed block never reopens: a block is closed only when the next start lies past its end. Every interval after that starts even further right, so none of them can reach back into it.
How to spot this pattern

When a problem hands you ranges and asks you to combine, count or cover them, sort first and ask what the sort key buys you. Sorting by start puts touching ranges side by side, which is exactly what merging needs.

03

Approach

Try it first

Before reading on, sort a small list by start and merge it by hand. Notice which interval you compare each new one against, and decide what makes you sure an earlier block is finished. Aim for O(n log n).

1

Sort by start

Sort intervals by their start value. After that, the intervals that overlap each other sit side by side, so you never need to look back past the block you are building.

2

Open the first block

Put the first sorted interval into a result list merged. The last entry of merged is the only block that can still grow; every entry before it is finished.

3

Grow the block on overlap

For each next interval, if its start is at most the block's end, set the block's end to the larger of the two ends. Both intervals now live inside one block, and nothing is appended.

4

Start a new block on a gap

If the next interval starts after the block's end, append it to merged as a new block. The previous block is now final, because every remaining interval starts at this point or later.

5

Return the blocks

When the loop ends, merged holds every block, in order of start. The open block is already inside the list, so there is no last interval to append after the loop.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def merge(self, intervals):
▶3 intervals.sort(key=lambda x: x[0])
▶4 merged = [intervals[0]]
▶5 for start, end in intervals[1:]:
▶6 if start <= merged[-1][1]:
▶7 merged[-1][1] = max(merged[-1][1], end)
▶8 else:
▶9 merged.append([start, end])
▶10 return merged
1 to 38 to 102 to 615 to 18024681012141618merged4 intervals, not sorted yet
intervals4input order
Here the intervals are in input order. An interval that overlaps 1 to 3 could be anywhere in the list, so a single pass in this order could close a block too early.
1 to 32 to 68 to 1015 to 18024681012141618mergedsorted by start
order1, 2, 8, 15starts, left to right
Sorted by start. Now any interval that overlaps the block being built comes straight after it, because each later interval starts at the same point or further right.
block ends at 31 to 32 to 68 to 1015 to 18024681012141618mergedopen a block: 1 to 3
block1 to 3still open
The first interval starts the first block. The last block in merged is the only one that can still grow; nothing before it will change again.
block ends at 61 to 32 to 68 to 1015 to 18024681012141618mergedstarts at 2, block ends at 3 → extend to 6
block1 to 6end grew
It starts at 2, no later than the block's end 3, so it overlaps. It reaches further, to 6, so the block grows to end at 6.
block ends at 101 to 32 to 68 to 1015 to 18024681012141618mergedstarts at 8, after 6 → new block
closed1 to 6final
block8 to 10new
It starts at 8, past the block's end 6, so there is a gap. The old block is final: every interval still to come starts at 8 or later, so none can reach back to 6.
block ends at 181 to 32 to 68 to 1015 to 18024681012141618mergedstarts at 15, after 10 → new block
closed8 to 10final
block15 to 18new
It starts at 15, past the block's end 10, so there is a gap. The old block is final: every interval still to come starts at 15 or later, so none can reach back to 10.
1 to 32 to 68 to 1015 to 18024681012141618mergedanswer: 3 intervals
merged[[1, 6], [8, 10], [15, 18]]returned
Every interval has been placed into a block, so merged is the answer: [[1, 6], [8, 10], [15, 18]].
05

Common pitfalls

Sorting by end instead of start

✗ Wrong
intervals.sort(key=lambda x: x[1])
✓ Right
intervals.sort(key=lambda x: x[0])

On [[2, 3], [4, 5], [1, 10]] the end order is unchanged, and the sweep returns all three intervals. The wide [1, 10] covers both others but arrives last, after their blocks were closed. The right answer is [[1, 10]].

Copying the new end instead of taking the larger one

✗ Wrong
merged[-1][1] = end
✓ Right
merged[-1][1] = max(merged[-1][1], end)

On [[1, 10], [2, 3]] the block shrinks to [1, 3] and the points 4 to 10 vanish. Sorting orders the starts only; a later interval can still end earlier.

Using a strict comparison for overlap

✗ Wrong
if start < merged[-1][1]:
✓ Right
if start <= merged[-1][1]:

On [[1, 4], [4, 5]] the strict test returns two intervals, but they share the point 4, so the expected answer is [[1, 5]].

06

Edge cases

Zero-length intervals, such as [[2, 2], [2, 2]]

The second start, 2, is not past the block's end, 2, so the two merge into [[2, 2]].

Intervals that already do not overlap

Every comparison finds a gap, so each interval becomes its own block and the output is the sorted input.

07

Complexity

Time
O(n log n)
Space
O(n)
The sort costs O(n log n) and the sweep O(n). The output can hold all n intervals; apart from it, only the sort's own working memory is used.
08

Merge Intervals FAQ

Can intervals be merged without sorting?

Only by paying for the value range. With ends up to 10⁴ you could record every start and end on an array of that size and sweep it in O(n + range). Zero-length intervals and shared endpoints make that marking fiddly, so sorting is the usual answer.

How is this different from Insert Interval?

Insert Interval gives you a list that is already sorted and free of overlaps, plus one new interval. You skip the sort, copy the intervals that end before the new one, merge the ones that touch it, and copy the rest, all in O(n).

Does the Python version change the input?

Yes. It sorts intervals in place, and merged holds the same inner lists, so growing a block also edits the caller's interval. Copy the list first if the caller still needs the original.