Pipeline task ordering (topological sort)
Problem
deps maps each task to its prerequisite tasks; tasks that appear only as prerequisites are still included. Return an order in which every prerequisite comes before the tasks that depend on it. Whenever several tasks are ready, take the lexicographically smallest first. Raise ValueError on a cycle.
Signature
def topo_order(deps: dict[str, list[str]]) -> list[str]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> topo_order({'train': ['features'], 'features': ['ingest'], 'evaluate': ['train']}) == ['ingest', 'features', 'train', 'evaluate']
True
>>> topo_order({'b': [], 'a': []}) == ['a', 'b']
TrueHints
Kahn’s algorithm with a min-heap for ready tasks (lexicographically smallest first).
Include prerequisite-only nodes; detect cycles by output length.
Raise ValueError on a cycle.
Reference solution
from collections import defaultdict
import heapq
def topo_order(deps):
nodes = set(deps)
for v in deps.values():
nodes.update(v)
indeg = {n: 0 for n in nodes}
children = defaultdict(list)
for t, ds in deps.items():
for d in ds:
children[d].append(t)
indeg[t] += 1
h = [n for n in nodes if indeg[n] == 0]
heapq.heapify(h)
out = []
while h:
n = heapq.heappop(h); out.append(n)
for c in children[n]:
indeg[c] -= 1
if indeg[c] == 0:
heapq.heappush(h, c)
if len(out) != len(nodes):
raise ValueError("cycle")
return outWhat a strong solution covers
- Kahn’s algorithm with a min-heap, O((V + E) log V).
- Includes prerequisite-only nodes.
- Detects cycles by output length.
- Discusses parallel scheduling by levels and retries/idempotency in orchestrators.
Common mistakes
- missing nodes that never appear as keys
- DFS without cycle detection (infinite recursion).