Problem overview
The method merge receives a list intervals of [start, end] lists. It merges every group of overlapping intervals and returns the intervals that remain, 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]. The input isn't sorted, and it holds between 1 and 100,000 intervals. The statement asks for O(n log n) time.
For [[1, 3], [2, 6], [8, 10], [15, 18]] the result is [[1, 6], [8, 10], [15, 18]]: the first two overlap and the others stand alone.
Approach: sort by start, then extend the last interval
Checking every pair and merging repeatedly is slow and awkward. Sorting makes the problem simple: after sorting by start, the intervals that overlap come one after another. Sweep through them while keeping a list of merged intervals. The last merged interval is the one still growing, and the next interval either:
- starts after it ends, so it can't overlap anything merged so far and begins a new merged interval, or
- starts at or before its end, so it overlaps, and the last merged interval is stretched to cover it.
Sorting costs O(n log n) and the sweep is one pass.
Step by step
- Sort
intervalsby start withsortandkey=lambda interval: interval[0]. - Create an empty list
merged. Its last interval is the one that may still grow. - Loop over
intervalsand unpack each one intostartandend, so the body doesn't need[0]or[1]. - Test whether this interval begins a new one:
mergedis empty (not merged), ormerged[-1][1] < start, meaning the last merged interval ends before this one starts. Use<, not<=, because touching intervals merge. - Append
[start, end]tomergedin that case. It is now the newest merged interval. - Otherwise extend the last interval: set
merged[-1][1]tomax(merged[-1][1], end). Keep the larger end, since an interval can lie completely inside the last one, like[2, 3]inside[1, 10], and then the end must stay 10. - Return
merged. It is in order of start, as the problem asks.
The solution in Python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda interval: interval[0])
merged = []
for start, end in intervals:
if not merged or merged[-1][1] < start:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
return merged
Here is the sweep on [[6, 8], [1, 9], [2, 4], [4, 7]]. After sorting the list is [[1, 9], [2, 4], [4, 7], [6, 8]], and merged evolves like this:
start | end | merged afterwards |
|---|---|---|
| 1 | 9 | [[1, 9]] |
| 2 | 4 | [[1, 9]] |
| 4 | 7 | [[1, 9]] |
| 6 | 8 | [[1, 9]] |
Every interval fits inside [1, 9], so the answer is [[1, 9]].
Python details worth knowing:
sort()reorders the caller's list and returnsNone;sorted()would return a new list instead.- Unpacking.
for start, end in intervalsassigns the two numbers of each inner list to two names. It works because every inner list has exactly two items. - Negative indexes.
merged[-1]is the last item. On an empty list it raisesIndexError, which is whynot mergedcomes first:orstops at the first true operand, somerged[-1]is never evaluated for an empty list. - Why
[start, end]and not the original list. The solution appends a new list, so extendingmerged[-1][1]changes the new list and not the caller's inner lists.
Complexity
Time: O(n log n) for the sort plus O(n) for the sweep. Space: O(n) for merged in the worst case, when nothing overlaps (not counting the sort's internal buffer).
Edge cases and common mistakes
- Touching intervals.
[[1, 4], [4, 5]]gives[[1, 5]]. Using<=in the test would keep them apart. - An interval inside another.
[[1, 10], [2, 3]]gives[[1, 10]]. Setting the end toendinstead of the larger value would shrink the result to[[1, 3]]. - No overlaps.
[[1, 2], [3, 4]]comes back unchanged. - A single interval.
[[5, 5]]gives[[5, 5]]. - Same start.
[[1, 4], [0, 4]]gives[[0, 4]]. - Forgetting to sort. The sweep only compares with the last merged interval, so it needs the sorted order. Without the sort,
[[1, 3], [8, 10], [2, 6]]gives[[1, 3], [8, 10]], which loses the overlap of[1, 3]and[2, 6]. The correct answer is[[1, 6], [8, 10]].
Testing
[[1, 3], [2, 6], [8, 10], [15, 18]]gives[[1, 6], [8, 10], [15, 18]].[[1, 4], [4, 5]]gives[[1, 5]].[[6, 8], [1, 9], [2, 4], [4, 7]]gives[[1, 9]].[[1, 2], [3, 4]]gives[[1, 2], [3, 4]].[[1, 4], [0, 0]]gives[[0, 0], [1, 4]].
