Data structures

Topological Sort

Kahn’s algorithm repeatedly removes nodes with in-degree zero. Watch the order emerge, or detect that a cycle makes ordering impossible.

5 minLevel 2/3The interactive stage stays ad-free.
Removed0 / 8Order—CycleUnknown
0in 01in 02in 03in 04in 05in 06in 07in 0

Kahn’s algorithm repeatedly takes a node with in-degree zero, removes its outgoing edges, and appends it to the order. If every node is removed, the graph has no cycle.

What you are seeing

1

A topological order only exists for a directed acyclic graph (DAG).

2

Kahn’s algorithm starts with nodes that have in-degree zero, removes them, and decreases their neighbors’ in-degrees.

3

If some nodes never reach in-degree zero, the graph contains a cycle.

Why it matters

Topological sorting powers build systems, package managers, course prerequisite planning, and task scheduling.

Complexity & details

Time: O(V + E). Space: O(V).

Frequently asked questions

Can a graph have multiple topological orders?+

Yes. Whenever multiple nodes have in-degree zero, their relative order is not forced, so several valid orders exist.

How does it detect cycles?+

If the output order contains fewer than V nodes after the queue empties, the remaining nodes form or depend on a cycle.