LearnCoding

Pipeline task ordering (topological sort)

EasyGraphs, Topological sort, MLOps

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']
True

Solve it in your own editor; nothing on this page runs code.

Hints

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 out

What 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).

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.