Topological Sort
GraphsavgO(V + E)worstO(V + E)spaceO(V)
Start every in-degree at 0, then count each node's incoming edges
1 / 33
Nodes8
Source
Edges (directed: A>B)
How it works
Kahn's algorithm orders a directed acyclic graph so every edge points forward: it repeatedly outputs a node with no remaining incoming edges and deletes that node's outgoing edges. Each in-degree that drops to zero releases a new node into the queue; if the queue empties early, the graph has a cycle.
Complexity
- Best
- O(V + E)
- Average
- O(V + E)
- Worst
- O(V + E)
- Space
- O(V)