Python coding

Add a range to sorted ranges

ranges is a list of closed ranges [start, end], sorted by start, where no two overlap or touch. Add the range new and return the list still sorted and still without overlaps, merging new with every range it overlaps. Ranges that share an endpoint, like [1, 4] and [4, 6], count as overlapping.

ranges may be empty and values can be negative. Aim for one O(n) pass, without sorting again.

  • add_range([[1,3],[6,9]], [2,5]) → [[1,5],[6,9]]
  • add_range([[0,2],[4,6],[8,9],[11,15]], [5,12]) → [[0,2],[4,15]]
  • add_range([[1,4],[9,12]], [6,7]) → [[1,4],[6,7],[9,12]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The list is already sorted, so no sort is needed: walk it once and decide, for each range, where it sits relative to new.

Hint 2

A range that ends before new starts goes to the output untouched; so does one that starts after new ends. Everything else overlaps new.

Hint 3

Absorb each overlapping range by widening new: start = min(...), end = max(...). Without max, adding [3, 4] to [1, 10] shrinks it.

Solution and why it works
pythonO(n) · O(n)
def add_range(ranges: list[list[int]], new: list[int]) -> list[list[int]]:
    start, end = new
    before, after = [], []
    for s, e in ranges:
        if e < start:
            before.append([s, e])            # ends before `new` starts
        elif s > end:
            after.append([s, e])             # starts after `new` ends
        else:                                # overlaps or touches: absorb it
            start, end = min(start, s), max(end, e)
    return before + [[start, end]] + after

Because the input is sorted and disjoint, every range falls into one of three groups, in order: entirely before new, overlapping it, or entirely after. One pass copies the first and last groups and folds the middle one into new with min and max: O(n), no sort. The traps are the comparisons: with closed ranges, [1, 4] and [4, 8] overlap, so only end < start means "before"; and widening without max shrinks a range that already contains new.