10/42
Part 3 of 8 · MergingLearn and do

Inserting one block into a sorted calendar is O(n), with no new sort

A calendar holds disjoint busy blocks, sorted. A new block arrives. You don't need to sort again. Copy the blocks that end before it starts, swallow every block that overlaps it into one, then copy the rest:

def insert(blocks, new):
    start, end = new
    out, i = [], 0
    # ends before the new one starts
    while i < len(blocks) and blocks[i][1] < start:
        out.append(blocks[i])
        i += 1
    # overlaps or touches it: swallow
    while i < len(blocks) and blocks[i][0] <= end:
        start, end = min(start, blocks[i][0]), max(end, blocks[i][1])
        i += 1
    out.append((start, end))
    # starts after it ends
    out.extend(blocks[i:])
    return out


blocks = [(1, 3), (5, 7), (9, 12), (14, 16)]
print(insert(blocks, (6, 10)))
print(insert(blocks, (3, 4)))
Predict

Insert (6, 10) into the sorted blocks (1, 3), (5, 7), (9, 12) and (14, 16). How many blocks are there after?

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