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

Sort the events you know up front, and use a heap when one event creates others

Sort or heap for the replay? If every event is known when the replay starts, sort them once: O(n log n), done in C. A heap earns its place when handling one event creates others, like a job that finishes and frees a machine for the next one. The heapq docs describe that use: a scheduler whose heap holds all the incoming events, with the smallest scheduled time coming off first.

The practice problem uses both:

  • The spends are all known, so they're sorted.
  • The credits are a heap keyed by expiry. Which credit pays depends on which ones have started and what's left of each, and that changes at every step of the replay.

In the editor, write finish_time(durations, machines): jobs run in the order given, each on the machine that frees up soonest. The heap free holds the time each machine is next free, and the answer is when the last job ends.