IntermediateSorting

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
CallExpected
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]]
Show solution
Python
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 out

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.