Merge every pair of overlapping ranges.
Start with the concrete trace below. It shows the state the algorithm must carry as it runs.
Problem trace
Merge Intervals: Sort ranges by start; compare each range with the last merged end, extending on overlap or appending on a gap.
- 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.
Pattern: Sort by start, then scan.
Simple idea: Compare each range with the last merged range. Overlap extends the last end. No overlap starts a new result range.
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
Cost: time and answer space.