Task Ordering with Topological Sort

medium
Unit 8 · Graphs I0/2 to milestone

Build systems, data pipelines and agent workflows all need to run tasks after the tasks they depend on. That ordering is a topological sort of a directed acyclic graph.

Implement topo_sort(deps), where deps maps each task to the list of tasks it depends on. Return a list containing every task exactly once, with each task after all its dependencies.

Rules

  • Tasks may appear only as dependencies and not as keys. Include them too.
  • When several tasks are ready at once, take the alphabetically smallest first, so the answer is unique.
  • If there's a cycle, raise ValueError.

Example

topo_sort({"deploy": ["build", "test"], "test": ["build"], "build": ["install"], "lint": ["install"]})
# ['install', 'build', 'lint', 'test', 'deploy']
#graphs#dag#scheduling3 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Task Ordering with Topological Sort · TechGradify