Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Graphs and connections
EXPERIMENT 40 / 66

Put prerequisites before the work.

Order a dependency DAG and explicitly reject cycles.

BY NAVAN SAMI◷ 9 MIN READCOREALGORITHM

01 Model the idea

A topological order places every directed prerequisite edge before its dependent vertex. Such an order exists exactly for directed acyclic graphs. Kahn’s algorithm repeatedly removes a zero-indegree vertex, updating the remaining dependency counts. Multiple valid orders can exist, so tie-breaking is part of the result contract when deterministic output matters.

THE THING THAT MUST STAY TRUE

Each emitted vertex has no incoming edge from an unprocessed vertex.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
COUNT incoming edges
ENQUEUE zero-indegree vertices
REMOVE one and decrement its dependents
REJECT if not all vertices were removed

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

topological_order.py
from collections import deque
def topological(graph):
    degree = {node: 0 for node in graph}
    for neighbours in graph.values():
        for node in neighbours: degree[node] += 1
    queue = deque(node for node in graph if degree[node] == 0)
    result = []
    while queue:
        node = queue.popleft(); result.append(node)
        for neighbour in graph[node]:
            degree[neighbour] -= 1
            if degree[neighbour] == 0: queue.append(neighbour)
    if len(result) != len(graph): raise ValueError("Dependency cycle")
    return result
print(topological({"design": ["build"], "build": ["test"], "test": []}))
↳ EXPECTED OUTPUT
['design', 'build', 'test']
  1. 1

    Indegree counts prerequisites still present in the remaining graph. Zero means a vertex can safely appear next.

  2. 2

    Removing a vertex decreases each dependent’s count. Each edge is processed once in this adjacency-list version.

  3. 3

    A final result shorter than the vertex count proves some cycle blocked progress. For a reproducible smallest-key order, use a heap instead of a queue and account for its logarithmic cost.

04 Count the cost

TIME

O(V + E) with a queue

SPACE

O(V) counts, queue and output

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Validate an order by checking that every prerequisite appears before its dependent.

Reveal one possible solution +
one_possible_solution.py
graph = {"design": ["build"], "build": ["test"], "test": []}
order = ["design", "build", "test"]
position = {node: i for i, node in enumerate(order)}
assert set(position) == set(graph)
assert all(position[u] < position[v] for u in graph for v in graph[u])
print("Dependency order verified")

06 Check your reasoning

QUICK SIGNAL CHECK

What does a zero indegree mean during Kahn’s algorithm?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.