Practice in Lab: Topological Sort →
Order tasks with depth-first topological sort
Build steps, course prerequisites and spreadsheet formulas form directed graphs without cycles. A topological order lists every task after everything it depends on.
needs = {"test": ["build"],
"build": ["fetch"], "fetch": []}
# fetch, build, testThink before coding
Depth-first search can emit a node after all of its dependencies have been emitted. Three states detect cycles: unvisited, in progress and done. Meeting a node that is still in progress means a cycle, so no order exists. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
Your task
Write build_order(needs) where needs maps each task to the tasks it depends on. Return a list with dependencies first, visiting tasks and dependencies in the given order, or raise ValueError on a cycle.
The explanation opens here once every check passes.