Merge overlapping intervals
Task
Write merge(intervals). Each interval is [start, end]; the input is not sorted. Merge intervals that overlap or touch ([1, 3] and [3, 5] become [1, 5]) and return the result sorted by start.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
merge([[1, 3], [2, 6], [8, 10], [15, 18]]) | [[1, 6], [8, 10], [15, 18]] |
merge([[5, 7], [1, 3], [3, 4]]) | [[1, 4], [5, 7]] |
merge([]) | [] |
merge([[1, 10], [2, 3]]) | [[1, 10]] |
- Sort by start first; then you only ever compare with the last merged interval.
- When merging, keep the larger end:
[1, 10]already covers[2, 3].
Show solution
def merge(intervals):
out = []
for start, end in sorted(intervals):
if out and start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return outAfter sorting, overlapping intervals are adjacent, so one pass is enough: O(n log n) overall. The two usual slips are using < (touching intervals stay separate) and taking the new end instead of the max.
Why this works
After sorting, overlapping intervals are adjacent, so one pass is enough: O(n log n) overall. The two usual slips are using < (touching intervals stay separate) and taking the new end instead of the max.
Revise in the Python guide, or test yourself with the Python practice sets.