VLVisual Learner

Topological Sort

Time: O(V + E)Kahn's algorithm (queue)Directed acyclic graphs
–
Pseudocode
1indeg[v] ← number of edges coming into v
2queue ← every vertex with indeg 0
3while the queue is not empty:
4 u ← dequeue; append u to the order
5 for each edge u → v:
6 indeg[v] ← indeg[v] − 1; if it is now 0: enqueue v
7if 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

// Kahn's algorithm. graph[u][v] = 1 for an edge u -> v ("u before v").
function topologicalSort(graph) {
  const n = graph.length;
  const indeg = Array(n).fill(0);
  for (let u = 0; u < n; u++)
    for (let v = 0; v < n; v++) if (graph[u][v]) indeg[v]++;

  const queue = [];
  for (let v = 0; v < n; v++) if (indeg[v] === 0) queue.push(v);

  const order = [];
  while (queue.length) {
    const u = queue.shift();
    order.push(u);
    for (let v = 0; v < n; v++) {
      if (!graph[u][v]) continue;
      if (--indeg[v] === 0) queue.push(v);   // all of v's prerequisites done
    }
  }
  return order.length === n ? order : null;  // null: there is a cycle
}

// DFS alternative: append each vertex when it FINISHES, then reverse the list.

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