Combine overlapping closed intervals into disjoint ranges covering exactly the same points as the original intervals.
Problem
Input. A list intervals of closed integer ranges [start, end], each with start <= end.
Output. Return start-sorted, disjoint intervals whose union equals the union of all input ranges.
Rules. Closed intervals sharing an endpoint overlap and must merge.
Containment and repeated intervals do not add separate output ranges.
The reference may reorder the input list; empty input returns [].
Example. [[8, 10], [1, 3], [2, 6], [15, 18]] returns [[1, 6], [8, 10], [15, 18]].
For [[1, 2], [2, 3]], return [[1, 3]] because the ranges share point 2.
Picture
Sort to [1,3], [2,6], [8,10], [15,18].
The first two overlap, extending the open component to [1,6].
The gap before 8 closes that component permanently.
Every future start is at least 8, so it cannot overlap that earlier [1,6].
The next gap similarly closes [8,10] before [15,18].
After each prefix, output components are ordered, disjoint and cover exactly the processed ranges. Only the last component remains eligible for extension.
Problem trace
Sorted order limits the next overlap to the final merged component
- max
- 18
- order
- sorted by start
- index 0
- 1: [1,3]
- state
- not shown→merged = [[1,3]]
- order
- sorted by start→not shown
- index 0
- 1: [1,3]→merged [1,3]
- branch
- not shown→2 <= 3 -> overlap
- state
- merged = [[1,3]]→merged = [[1,6]]
- index 0
- merged [1,3]→merged [1,6]
- branch
- 2 <= 3 -> overlap→8 > 6 -> append
- state
- merged = [[1,6]]→merged = [[1,6],[8,10]]
- index 1
- current [2,6]→merged [8,10]
- branch
- 8 > 6 -> append→15 > 10 -> append
- result
- not shown→[[1,6],[8,10],[15,18]]
- state
- merged = [[1,6],[8,10]]→not shown
- Recognize it
- Use it when arbitrary ranges must be coalesced by overlap; sorting by start guarantees that any range able to overlap the current merged component appears before a later gap.
- Keep true
- Before each current interval, merged is sorted, disjoint, and exactly covers all processed ranges; only merged[-1] can overlap current because starts are nondecreasing.
- Reuse it
- Sorting can turn a global overlap problem into a local frontier check: preserve a completed prefix and keep only the final component open for possible extension.
Reference drawing
Problem trace
Sorted order limits the next overlap to the final merged component
Execution trace
- max
- 18
- order
- sorted by start
- index 0
- 1: [1,3]
- state
- not shown→merged = [[1,3]]
- order
- sorted by start→not shown
- index 0
- 1: [1,3]→merged [1,3]
- branch
- not shown→2 <= 3 -> overlap
- state
- merged = [[1,3]]→merged = [[1,6]]
- index 0
- merged [1,3]→merged [1,6]
- branch
- 2 <= 3 -> overlap→8 > 6 -> append
- state
- merged = [[1,6]]→merged = [[1,6],[8,10]]
- index 1
- current [2,6]→merged [8,10]
- branch
- 8 > 6 -> append→15 > 10 -> append
- result
- not shown→[[1,6],[8,10],[15,18]]
- state
- merged = [[1,6],[8,10]]→not shown
- Recognize it
- Use it when arbitrary ranges must be coalesced by overlap; sorting by start guarantees that any range able to overlap the current merged component appears before a later gap.
- Keep true
- Before each current interval, merged is sorted, disjoint, and exactly covers all processed ranges; only merged[-1] can overlap current because starts are nondecreasing.
- Reuse it
- Sorting can turn a global overlap problem into a local frontier check: preserve a completed prefix and keep only the final component open for possible extension.
On overlap, retain the larger end.
For [1,10] followed by [2,3], replacing the end with 3 would lose covered points.
On a gap, append a fresh component.
Code
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
if not intervals:
return []
ordered = sorted(intervals)
merged = [ordered[0].copy()]
for start, end in ordered[1:]:
if start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
sorted preserves input order and rows; the copied first row prevents later frontier updates from mutating an input row.
Every returned row is newly allocated.
Empty input returns [].
Sorting takes time. Answer storage is ; sorted lists, slicing and sorting workspace also take space. This is union, not maximum compatible selection or peak simultaneous resource demand.
Change the Touching Policy
New task: Coalesce only positive-width overlaps, leaving merely touching ranges separate.
Picture and change: Use strict start < last_end and require positive-width inputs.
This changes grouping policy, not necessarily the covered real set.
def merge_strict_overlaps(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start < merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
Check: [[1,2],[2,3],[2,4]] returns [[1,2],[2,4]].
The first range only touches the second group; the equal-start ranges have positive-width overlap and merge.
Neither endpoint policy should be silently imported from a scheduling task.
Use when: Shared endpoints alone must not coalesce groups.
Change to Integer Coverage
New task: Count distinct integer coordinates covered by closed integer ranges.
Picture and change: First obtain disjoint union components.
Each contributes end-start+1 integer points without enumerating them.
def covered_integer_points(intervals):
return sum(end - start + 1
for start, end in merge_intervals(intervals))
Check: [[1,3],[2,6],[8,10]] covers six points 1..6 and three points 8..10: total 9.
Continuous length would omit the +1 and answer a different question.
Both adaptations retain the sorting bound and fresh union rows.
Use when: Union representation becomes a discrete coverage count.
Transfer Check
Why cannot earliest-finish scheduling replace this scan?
Answer
Scheduling discards overlapping ranges to maximize a compatible subset. Union must preserve every covered point, so it extends components instead of rejecting their coverage.