Topological Sort (Kahn's BFS)
Order the vertices of a DAG so every edge points forward. Kahn's algorithm uses in-degrees.
Open on GeeksforGeeks ↗Intuition
A vertex is ready to be output only when every prerequisite is already out — and 'no remaining prerequisites' is exactly in-degree == 0. Start with all such vertices, and each time you output one, remove its edges, which may free others. If the process stalls before covering every vertex, the leftovers form a cycle.
Peel off vertices with no remaining prerequisites. In-degree zero means nothing blocks you; removing a vertex decrements its neighbours, which may free them in turn. The count check at the end doubles as cycle detection — a cycle can never reach in-degree zero, so the queue stalls early.
Approach
Count incoming edges
Scan every adjacency list once, incrementing indeg[v] for each edge u → v. Vertices with in-degree 0 depend on nothing and can go first.
Peel in waves
Queue all zero-degree vertices. Pop one, append it to the order, and decrement the in-degree of each target — any that hits 0 is newly unblocked and joins the queue.
Cycle detection for free
In a DAG every vertex eventually reaches in-degree 0. If the output is shorter than V, the remaining vertices each still wait on another — that is a cycle, so no ordering exists.
Solution & live demo
Common pitfalls
Not detecting the stall
return order
if len(order) < n:
return []
return orderA cyclic graph produces a partial order and the algorithm terminates quietly. Comparing the output length against n is the whole cycle test — no separate DFS colouring needed.
Enqueuing on every decrement
indeg[u] -= 1 q.append(u)
indeg[u] -= 1
if indeg[u] == 0:
q.append(u)A vertex with three prerequisites would enter the queue three times and be emitted before its dependencies are satisfied. It becomes ready only on the transition to zero.
Counting outgoing edges as in-degree
for u in range(n):
indeg[u] += len(adj[u])for u in range(n):
for v in adj[u]:
indeg[v] += 1In-degree counts edges arriving at a vertex. Counting the adjacency list's length measures out-degree, which inverts the dependency direction and yields a reversed or invalid order.
Edge cases
Fewer than V vertices are output; return empty / report failure.
Any is acceptable; queue order decides which one appears.
Every vertex starts at in-degree 0 — any permutation is valid.