Reading preferences
Concept

Topological Sorting

Order tasks so each prerequisite appears before its dependent.

python, graph, topological sort, dependencies

Honour prerequisites

Represent a dependency as an arrow from prerequisite to dependent. Repeatedly remove a task with no remaining prerequisites, then release its outgoing arrows. This is Kahn's algorithm.

Python illustration

from collections import deque

def task_order(nodes, edges):
    outgoing = {node: [] for node in nodes}
    indegree = {node: 0 for node in nodes}
    for before, after in edges:
        outgoing[before].append(after)
        indegree[after] += 1
    ready = deque(node for node in nodes if indegree[node] == 0)
    order = []
    while ready:
        node = ready.popleft()
        order.append(node)
        for after in outgoing[node]:
            indegree[after] -= 1
            if indegree[after] == 0:
                ready.append(after)
    if len(order) != len(nodes):
        raise ValueError("dependency cycle")
    return order

print(task_order(["A", "B", "C"], [("A", "C"), ("B", "C")]))

Prepared output: ['A', 'B', 'C']. A and B may exchange places in another valid ordering.

See the reasoning

Release prerequisites

Follow the queue as prerequisites are removed. This is a prepared demonstration, not live code execution.

Find ready tasks

A → C and B → C
  1. ReadyA, BCurrent focus
  2. C prerequisites2
  3. Outputempty

A and B have no incoming prerequisites.

Detect cycles and account for storage

Every queued node has no incoming edge from an unprocessed node. Removing it preserves each prerequisite-before-dependent rule. If nodes remain after the queue empties, a cycle prevents a complete ordering. With V unique hashable nodes and E edges, time and extra space are O(V + E). This example assumes a reusable sequence of unique nodes and edges whose endpoints are present; unknown endpoints raise KeyError. Duplicate edges are counted and removed consistently. Python's graphlib offers a library alternative.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does an edge A to B mean here?
2. Which nodes can enter the queue?
3. What indicates a cycle in this implementation?
4. Is a topological ordering always unique?

References and further reading