20/40
Part 5 of 8 · Merging and schedulingLearn and do

Always take what's due soonest

The third pattern, and the one the practice problem runs on. Key the heap by when each thing is due: a deadline, an expiry, an end time. Then heap[0] is always the next thing to deal with. Here it's rooms and meetings.

The question: given meetings as (start, end) pairs, each holding a room for start <= t < end, how many rooms do you need? The obvious answer keeps a list of rooms, each with the time it's next free. Each meeting, in start order, takes the first room that's free:

def rooms_by_scan(meetings):
    # when each room is next free
    rooms = []
    for start, end in sorted(meetings):
        for i, free_at in enumerate(rooms):
            if free_at <= start:
                rooms[i] = end
                break
        else:
            rooms.append(end)
    return len(rooms)


meetings = [(9, 10), (9, 11), (10, 11), (10, 12), (11, 13), (12, 14)]
print(rooms_by_scan(meetings))
Predict

Six meetings: 9 to 10, 9 to 11, 10 to 11, 10 to 12, 11 to 13 and 12 to 14. How many rooms do they need?

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