Topological Sort (Kahn's BFS)
Topological Sort (Kahn's BFS) is a GFG problem (Medium). The graph has V vertices, 0 to V - 1, and each edges[i] = [u, v] is a directed edge from u to v.
- Return all
Vvertices in an order where every edge points forward: for eachu → v,uis listed beforev. - Any valid order is accepted, and the input is promised to be a DAG.
This page builds the order with Kahn's algorithm, which works from the vertices that nothing points to. With up to 10⁵ edges, each vertex and each edge may be handled only a constant number of times.
- 2 <= V <= 5 × 10³
- 1 <= E = edges.length <= min(10⁵, V(V − 1) / 2)
- 0 <= edges[i][0], edges[i][1] < V
- The graph is a directed acyclic graph (DAG)
Intuition
Read each edge u → v as a rule: v has to wait for u. The in-degree of a vertex is the number of rules it is still waiting on.
A vertex with in-degree 0 waits on nothing, so it can be written down right now. Writing it down settles every rule that starts at it, so each vertex it points to waits on one fewer, and some of them drop to 0 and become ready.
Keep writing down a ready vertex and crossing out its outgoing edges. A vertex is only written after every vertex that points at it, so every edge ends up pointing forward.
"List the items so that each one comes after everything it depends on" is a topological sort. Build systems, package installs and task schedulers all need one, and Kahn's version also tells you when the dependencies loop.
Approach
Before reading on, decide which vertex can safely go first, and what has to change after you write it down. Then think about how you would notice, at the end, that a loop of edges stopped some vertices. Aim for O(V + E).
Count in-degrees while building the lists
For each edge [u, v], add v to adj[u] and add 1 to indeg[v]. adj[u] lists the vertices that u releases when it is written down, and indeg[v] counts how many vertices must come before v.
Queue every vertex with in-degree 0
Push each vertex whose count is 0 into a queue. Nothing points at these vertices, so any of them can open the order. A deque keeps each pop from the front O(1) in Python.
Pop a vertex and append it
Take the front of the queue and append it to order. A vertex only enters the queue after all of its predecessors were appended, so its position can never break an edge.
Release the vertices it points to
For each v in adj[u], subtract 1 from indeg[v], because one vertex it waits on is now placed. When the count reaches 0, push v onto the queue: nothing blocks it any more.
Check the count at the end
When the queue is empty, order holds all V vertices if the graph is a DAG. If it holds fewer, the missing vertices sit on or behind a cycle, so no valid order exists and the code returns an empty list.
Code in Python, C++ and Java
Common pitfalls
Counting the in-degree on the wrong end
for u, v in edges:
adj[u].append(v)
indeg[u] += 1for u, v in edges:
adj[u].append(v)
indeg[v] += 1In-degree counts the edges coming into a vertex. With edges = [[0, 1]] the wrong version gives vertex 0 a count of 1 and vertex 1 a count of 0, so vertex 1 is written first and vertex 0 is never freed.
Queuing a vertex before its count reaches 0
for v in adj[u]:
indeg[v] -= 1
q.append(v)for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)A vertex can have several predecessors. With edges 0 → 2, 0 → 1, 1 → 2, popping 0 queues 2 at once, so the output starts 0, 2, 1 and the edge 1 → 2 points backwards. Vertex 2 is also queued a second time later.
Edge cases
Its count starts at 0, so it is queued with the first batch and still appears exactly once in the order.
indeg[v] counts it twice and adj[u] holds v twice, so popping u subtracts 2 and the count still lands on 0 at the right moment.
Complexity
Topological Sort (Kahn's BFS) FAQ
Why do leftover vertices prove there is a cycle?
Every leftover vertex still has a count of at least 1, and the edges behind that count must come from other leftover vertices, because placed vertices already took theirs back. So from any leftover vertex you can step back to a leftover predecessor, then again, forever. With only V vertices, the walk must revisit one, and that repeat closes a cycle.
How do I get the smallest topological order in dictionary order?
Replace the queue with a min-heap so that, out of all ready vertices, the smallest number always comes out first. With edges 2 → 0 and 1 → 0, the queue may give 2, 1, 0, while the heap gives 1, 2, 0. The cost rises to O(V log V + E).
Should I use Kahn's algorithm or DFS?
Both run in O(V + E). Kahn's algorithm is the topological sort BFS version: it needs no recursion, so a 5,000-vertex chain cannot overflow the stack, and the final count doubles as a cycle check. Popping the queue one batch at a time also gives the fewest rounds when ready jobs can run in parallel. DFS appends each vertex after its descendants and reverses the list at the end.