---
title: Pipeline task ordering (topological sort)
url: https://gurkanozkan.ai/learn/coding/mle-pipeline-task-ordering-topological-sort-36/
markdown: https://gurkanozkan.ai/learn/coding/mle-pipeline-task-ordering-topological-sort-36.md
kind: coding
difficulty: Easy
topics:
  - Graphs
  - Topological sort
  - MLOps
json: https://gurkanozkan.ai/api/learn/coding/mle-pipeline-task-ordering-topological-sort-36.json
robots: noindex
---

# Pipeline task ordering (topological sort)

`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

```python
def topo_order(deps: dict[str, list[str]]) -> list[str]: ...
```

## Examples

Each call and the value it should give.

```python
>>> topo_order({'train': ['features'], 'features': ['ingest'], 'evaluate': ['train']}) == ['ingest', 'features', 'train', 'evaluate']
True

>>> topo_order({'b': [], 'a': []}) == ['a', 'b']
True
```

## Hints

1. Kahn's algorithm with a min-heap for ready tasks (lexicographically smallest first).
2. Include prerequisite-only nodes; detect cycles by output length.
3. Raise ValueError on a cycle.

## Reference solution

```python
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.*
