8/42
Part 3 of 8 · MergingLearn and do

Sort by start, and one pass merges

Three questions run on the same pass over intervals sorted by start: merge them, insert one more, and find the gaps between them.

Sorted by start, a block can only overlap the merged block just before it

Three people's calendars, in half-open hours:

ana = [(9, 10), (12, 15)]
bo = [(10, 11), (12, 13), (16, 17)]
cy = [(13, 14), (15, 16)]


def merge(blocks):
    out = []
    for start, end in sorted(blocks):
        # starts by the time the last one ends
        if out and start <= out[-1][1]:
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out


print(merge(ana + bo + cy))
Predict

The busy blocks are (9, 10), (10, 11), (12, 13), (12, 15), (13, 14), (15, 16) and (16, 17), merged when they overlap or touch. How many blocks are left?

Pick one to see what it prints.
Pick an answer above to see the rest