AiTechWorlds
AiTechWorlds
Animate Kahn's topological sort removing in-degree-0 nodes from a DAG, with live order, in-degrees, and synced code.
from collections import deque
def topo_sort(adj, n):
indeg = [0] * n
for u in range(n):
for v in adj[u]: indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
u = q.popleft(); order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0: q.append(v)
return orderTopological Sort orders the nodes of a directed acyclic graph so that every edge points from an earlier to a later node. Kahn's algorithm repeatedly removes in-degree-0 nodes.
| Time | O(V + E) |
| Space | O(V) |
| Graph | Directed, unweighted |
The Topological Sort Visualizer animates how topological sorting works on a directed acyclic graph (DAG): Kahn's algorithm repeatedly removes nodes with in-degree 0 and outputs them, decrementing the in-degrees of their neighbors. It produces an ordering where every edge points from an earlier to a later node. The algorithm runs in O(V + E) time and O(V) space.
Generate a DAG
Click New Graph or set the node-count slider to create a random directed acyclic graph.
Play the animation
Press Play to watch in-degree-0 nodes output and in-degrees decrement.
Step and scrub
Use Step Forward/Back or the timeline to inspect each removal.
Read the synced code
The highlighted pseudocode line tracks Kahn's algorithm; switch tabs for C++, Java, Python, or JavaScript.
100% Private — No Server Required
All processing happens directly in your browser. No data is uploaded, stored, or transmitted to any server.
Last reviewed on June 14, 2026 by the AiTechWorlds Tools Team. All processing runs locally in your browser.