Any ready task can go next, so one graph can give several valid orders
When several tasks are ready at once, which one goes first?
Predict
Pop the newest ready task instead, from a stack. Which task comes first?
Two ways to take the ready tasks
queue: the oldest ready task first
fetch
→
docs
→
compile
→
assets
→
test
→
package
→
deploy
stack: the newest ready task first
docs
→
fetch
→
assets
→
compile
→
package
→
test
→
deploy
Both orders are valid.
The queue's order doesn't matter here, which is new. In a grid search, popleft made the first count the shortest. Here any ready task can go next. Order matters again further down, where you count rounds.
Python has this built in since 3.9, as graphlib.TopologicalSorter. Its graph dict maps each task to its prerequisites, the opposite way to unblocks. On the pipeline, list(TopologicalSorter(graph).static_order()) gave the same order as Kahn's loop with a queue. Mention it, then write the loop anyway: the counts are what the interviewer wants to watch you get right.
The editor holds stack_order, Kahn's loop with a list as a stack, and an empty library_order. Finish the first, and write the second with graphlib.
Pick an answer above to see the rest
Instructions
1
Finish stack_order(tasks, needs): put each popped task in the order, and push a task onto ready when its count reaches 0.
2
Write library_order(tasks, needs) with graphlib.TopologicalSorter, whose graph maps every task to the list of its prerequisites.