23/32
Part 6 of 7 · The worked exampleLearn and do

Walk the order backwards to get each task's latest finish

3. The insight. Run the same idea backwards. The forward pass gives each task's earliest finish and the done time. Then walk the order in reverse:

  • A task that nothing needs can finish as late as the done time.
  • Any other task must finish before each task that needs it has to start. The latest a task can start is its own latest finish minus its minutes.
  • So a task's latest finish is the smallest of those, and its slack is its latest finish minus its earliest.
def slack(tasks, needs, minutes):
    finish = earliest_finish(tasks, needs, minutes)
    done = max(finish.values(), default=0)
    unblocks, _ = build_graph(tasks, needs)
    latest = {}
    # every dependent comes first
    for task in reversed(kahn_order(tasks, needs)):
        latest[task] = min((latest[nxt] - minutes[nxt] for nxt in unblocks[task]), default=done)
    return {task: latest[task] - finish[task] for task in tasks}

earliest_finish is the forward pass from the checkpoint above. Reversing the order puts every task after the tasks that need it, so their latest finishes are final when it reads them. It's the forward pass with the arrows turned around, and max turned into min.

The editor holds a latest_finish with one bug, and the pipeline's minutes. Find the bug and fix it.