Topological Sort
Kahn’s algorithm repeatedly removes nodes with in-degree zero. Watch the order emerge, or detect that a cycle makes ordering impossible.
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
A topological order only exists for a directed acyclic graph (DAG).
Kahn’s algorithm starts with nodes that have in-degree zero, removes them, and decreases their neighbors’ in-degrees.
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.