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.
- 1 <= intervals.length <= 10⁴
- intervals[i].length == 2
- 0 <= starti <= endi <= 10⁴
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.
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.
Approach
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).
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Sorting by end instead of start
intervals.sort(key=lambda x: x[1])
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
merged[-1][1] = end
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
if start < merged[-1][1]:
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]].
Edge cases
[[2, 2], [2, 2]]The second start, 2, is not past the block's end, 2, so the two merge into [[2, 2]].
Every comparison finds a gap, so each interval becomes its own block and the output is the sorted input.
Complexity
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.