Topological Sort
–
Pseudocode
1indeg[v] ← number of edges coming into v2queue ← every vertex with indeg 03while the queue is not empty:4 u ← dequeue; append u to the order5 for each edge u → v:6 indeg[v] ← indeg[v] − 1; if it is now 0: enqueue v7if the order has fewer than V vertices: the graph has a cycle
Placed
0
Edges removed
0
in 2edges still coming inqueueready (yellow)placed in the order
What is a Topological Sort?
A topological order of a directed graph lists the vertices so that every edge points forward: for each u → v, u comes before v. If the edges mean "must happen before" (course prerequisites, build steps, tasks), a topological order is a valid schedule.
Kahn's algorithm repeatedly picks a vertex with no incoming edges left: nothing still has to happen before it. It goes next in the order, and its outgoing edges are removed, which may make more vertices ready. An order exists only if the graph has no cycle; vertices on a cycle never become ready.
Repeatedly take a vertex with nothing left before it, then remove its edges.
Using the Visualizer
- • The label in 2 is a vertex's in-degree: how many edges still point into it.
- • Yellow vertices are ready (in the queue); green ones are placed. Used edges fade out.
- • Add an edge that closes a loop in Edit graph and watch the cycle get reported in red.
How It Works
1. Count in-degrees
For each vertex, the number of edges coming in.
2. Queue the ready ones
Every vertex with in-degree 0.
3. Place and remove
Dequeue u, append it to the order, decrease the in-degree of each v with u → v; enqueue v when it hits 0.
4. Cycle check
Fewer than V vertices placed means the leftovers form a cycle.
Not unique: when several vertices are ready at the same time, any of them can go next, so a DAG usually has many valid orders.
Implementation
Properties & Complexity
Time Complexity
- • Adjacency list: O(V + E)
- • Adjacency matrix: O(V²)
Space & Properties
- • Space: O(V) for in-degrees and the queue
- • Bonus: detects cycles for free
Where It Is Used
- • Build systems (make, bundlers): compile dependencies first
- • Course planning: prerequisites before advanced classes
- • Spreadsheets: recompute cells after the cells they use
- • Package managers: install order of dependencies
Limitations
- • Only for DAGs: a cycle means there is no valid order
- • Not unique: many orders can be correct