9/32
Part 2 of 7 · Kahn's algorithmLearn and do

Each task is popped once and each pair handled once, so Kahn's is O(V + E)

Here is what that change is worth, timed on chains of tasks.

Tasks in the chainRescanKahn's
1,000144.8 ms0.30 ms
2,000611.2 ms0.61 ms
4,0002,402.0 ms1.31 ms
8,0009,987.5 ms2.52 ms

Each task goes on the queue once and comes off once. Each pair is handled once, when its prerequisite is popped and its task's count drops by one. On the chain of 8,000 that's 8,000 pops and 7,999 decrements, against the rescan's 32 million checks.

The times are from Python 3.12 on one laptop, best of 3 runs for the rescan and of 5 for Kahn's. Double the tasks and the rescan takes four times as long, O(V2)O(V^2), while Kahn's takes twice as long.

The editor holds Kahn's loop as kahn_work, with two counters that never move. Make pops and decrements count, and compare the totals with V and E.