Python coding

Combine overlapping ranges

Given a list of closed ranges [start, end] in any order, merge every group of ranges that overlap and return the result sorted by start. Ranges that only touch, like [1, 4] and [4, 5], count as overlapping.

Every range has start <= end, and values can be negative.

Besides the tests, one large input (4,200 ranges) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

  • merge_ranges([[1,3],[2,6],[8,10],[15,18]]) → [[1,6],[8,10],[15,18]]
  • merge_ranges([[1,4],[4,5]]) → [[1,5]]
  • merge_ranges([[1,10],[2,3]]) → [[1,10]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sort by start. Then a range can only overlap the last range you kept, never an earlier one.

Hint 2

If start <= last_end, extend the last range to max(last_end, end); otherwise append a new range.

Solution and why it works
pythonO(n log n) · O(n)
def merge_ranges(intervals: list[list[int]]) -> list[list[int]]:
    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 by start, a range can only overlap the last one kept, so one sweep decides everything: extend the last end or start a new range. The sort dominates at O(n log n). Two traps: extending without max() shrinks [1, 10] to [1, 3] when [2, 3] follows, and < instead of <= leaves touching ranges like [1, 4] and [4, 5] apart.