GeeksforGeeks Medium

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 V vertices in an order where every edge points forward: for each u → v, u is listed before v.
  • 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.

Constraints
  • 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)
graphtoposortbfsin-degree
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3 
▶4class Solution:
▶5 def topoSort(self, V, edges):
▶6 adj = [[] for _ in range(V)]
▶7 indeg = [0] * V
▶8 for u, v in edges:
▶9 adj[u].append(v)
▶10 indeg[v] += 1
▶11 
▶12 q = deque(x for x in range(V) if indeg[x] == 0)
▶13 order = []
▶14 while q:
▶15 u = q.popleft()
▶16 order.append(u)
▶17 for v in adj[u]:
▶18 indeg[v] -= 1
▶19 if indeg[v] == 0:
▶20 q.append(v)
▶21 return order if len(order) == V else []
0from 5from 41from 4from 32from 53from 24none5noneready queueemptyordercount the edges into each vertex
vertices6
edges6
Each column is a vertex. Every edge u → v becomes a token from u under v: one rule v is still waiting on. The number of tokens is the vertex's in-degree.
0from 5from 41from 4from 32from 53from 24none5noneready queue45ordernothing points at 4, 5 → queue
queue4, 5in-degree 0
Vertices with no tokens wait on nothing, so any of them can go first. Every other vertex has to wait until its column is empty.
0from 5from 41from 4from 32from 53from 24none5noneready queue5order4take 4 → place it 1st
u4front of the queue
order4
Vertex 4 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. It has edges to 0, 1, so those tokens go next.
0from 5from 41from 4from 32from 53from 24none5noneready queue5order40 still waits on 1 more → wait
in-degree of 01
queue5
The rule 4 before 0 is now met, so the token from 4 leaves column 0. Another token is still there, so 0 cannot be placed yet.
0from 51from 4from 32from 53from 24none5noneready queue5order41 still waits on 1 more → wait
in-degree of 11
queue5
The rule 4 before 1 is now met, so the token from 4 leaves column 1. Another token is still there, so 1 cannot be placed yet.
0from 51from 32from 53from 24none5noneready queueemptyorder45take 5 → place it 2nd
u5front of the queue
order4, 5
Vertex 5 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. It has edges to 2, 0, so those tokens go next.
0from 51from 32from 53from 24none5noneready queue2order452 waits on nothing now → queue it
in-degree of 20
queue2
The rule 5 before 2 is now met, so the token from 5 leaves column 2. That was its last token: 2 joins the back of the queue.
0from 51from 323from 24none5noneready queue20order450 waits on nothing now → queue it
in-degree of 00
queue2, 0
The rule 5 before 0 is now met, so the token from 5 leaves column 0. That was its last token: 0 joins the back of the queue.
01from 323from 24none5noneready queue0order452take 2 → place it 3rd
u2front of the queue
order4, 5, 2
Vertex 2 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. It has edges to 3, so those tokens go next.
01from 323from 24none5noneready queue03order4523 waits on nothing now → queue it
in-degree of 30
queue0, 3
The rule 2 before 3 is now met, so the token from 2 leaves column 3. That was its last token: 3 joins the back of the queue.
01from 3234none5noneready queue3order4520take 0 → place it 4th
u0front of the queue
order4, 5, 2, 0
Vertex 0 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. No edge starts at it, so no other column changes.
01from 3234none5noneready queueemptyorder45203take 3 → place it 5th
u3front of the queue
order4, 5, 2, 0, 3
Vertex 3 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. It has edges to 1, so those tokens go next.
01from 3234none5noneready queue1order452031 waits on nothing now → queue it
in-degree of 10
queue1
The rule 3 before 1 is now met, so the token from 3 leaves column 1. That was its last token: 1 joins the back of the queue.
01234none5noneready queueemptyorder452031take 1 → place it 6th
u1front of the queue
order4, 5, 2, 0, 3, 1
Vertex 1 leaves the queue and fills the next slot. It was only queued once its column was empty, so everything it waits on is already placed to its left. No edge starts at it, so no other column changes.
01234none5noneready queueemptyorder452031all 6 placed → return the order
placed6of 6
result4, 5, 2, 0, 3, 1
Every column emptied, so every edge points from an earlier slot to a later one. Other orders can be valid too; any one is accepted.
05

Common pitfalls

Counting the in-degree on the wrong end

✗ Wrong
for u, v in edges:
    adj[u].append(v)
    indeg[u] += 1
✓ Right
for u, v in edges:
    adj[u].append(v)
    indeg[v] += 1

In-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

✗ Wrong
for v in adj[u]:
    indeg[v] -= 1
    q.append(v)
✓ Right
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.

06

Edge cases

A vertex with no edges at all

Its count starts at 0, so it is queued with the first batch and still appears exactly once in the order.

The same edge listed twice

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.

07

Complexity

Time
O(V + E)
Space
O(V + E)
Each vertex is pushed and popped once, and each edge lowers one count once. The adjacency lists hold E entries; the counts, the queue and the order hold V each.
08

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.