Put prerequisites before the work.
Order a dependency DAG and explicitly reject cycles.
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.
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.
COUNT incoming edges
ENQUEUE zero-indegree vertices
REMOVE one and decrement its dependents
REJECT if not all vertices were removed03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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": []}))['design', 'build', 'test']
- 1
Indegree counts prerequisites still present in the remaining graph. Zero means a vertex can safely appear next.
- 2
Removing a vertex decreases each dependent’s count. Each edge is processed once in this adjacency-list version.
- 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
O(V + E) with a queue
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
Validate an order by checking that every prerequisite appears before its dependent.
Reveal one possible solution +
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
What does a zero indegree mean during Kahn’s algorithm?
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.