Skip to lesson

Topological sort

Topological sort orders vertices in a directed acyclic graph such that every prerequisite precedes its dependent tasks.

Kahn's algorithm using in-degrees and a queue

A topological sort orders the nodes of a directed acyclic graph so that every edge goes from an earlier node to a later one, such as courses before the courses that need them.

A topological sort linearly orders vertices of a directed acyclic graph. For every directed edge from u to v, vertex u must appear before vertex v. If a directed graph contains a cycle, no valid topological ordering exists.

Kahn's algorithm step-by-step trace

Step 1 of 5

0123
in0
0
in1
1
in2
1
in3
2
Compute in-degrees: 0 has 0, 1 has 1, 2 has 1, 3 has 2. Enqueue node 0 with 0 prerequisites.

Example 1 · Brute force: rescan for a ready vertex every round, O(V^2 + V * E)

Main.javaJava
import java.util.*;
public class Main {    public static void main(String[] args) {        int n = 4;        int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}};        int[] inDegree = new int[n];        for (int[] e : edges) inDegree[e[1]]++;
        boolean[] placed = new boolean[n];        List<Integer> order = new ArrayList<>();        for (int round = 0; round < n; round++) {            int pick = -1;            for (int v = 0; v < n && pick == -1; v++) {   // scan every vertex again                if (!placed[v] && inDegree[v] == 0) pick = v;            }            if (pick == -1) break;                         // a cycle: nothing is ready            placed[pick] = true;            order.add(pick);            for (int[] e : edges) {                        // scan every edge again                if (e[0] == pick) inDegree[e[1]]--;            }        }        System.out.println("Topological Order: " + order);    }}
Output
Topological Order: [0, 1, 2, 3]

What this code does

  • Each round scans all vertices to find one with no waiting prerequisites.
  • Then it scans all edges to lower the counts of that vertex's neighbours.
  • Kahn's queue removes both scans: ready vertices wait in a queue and only their own edges are touched.

Example 2 · Optimal: Kahn's algorithm, O(V + E) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    static int[] topologicalSort(int n, List<List<Integer>> adj) {        int[] inDegree = new int[n];        for (int u = 0; u < n; u++) {            for (int v : adj.get(u)) inDegree[v]++;        }
        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < n; i++) {            if (inDegree[i] == 0) q.offer(i);        }
        int[] order = new int[n];        int idx = 0;
        while (!q.isEmpty()) {            int u = q.poll();            order[idx++] = u;
            for (int v : adj.get(u)) {                inDegree[v]--;                if (inDegree[v] == 0) q.offer(v);            }        }
        return idx == n ? order : new int[0]; // Empty array indicates cycle    }
    public static void main(String[] args) {        int n = 4;        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        adj.get(0).add(1);        adj.get(0).add(2);        adj.get(1).add(3);        adj.get(2).add(3);
        int[] res = topologicalSort(n, adj);        System.out.println("Topological Order: " + Arrays.toString(res));    }}
Output
Topological Order: [0, 1, 2, 3]

What this code does

  • inDegree array tracks incoming prerequisites for each vertex.
  • Vertices with inDegree 0 enter the queue and decrement neighbours on removal.
  • Returns valid order [0, 1, 2, 3] in O(V + E) time.
  • Each vertex enters the queue once and each edge is visited once, so no round rescans the whole graph.

Kahn's algorithm computes this ordering using in-degrees and a FIFO queue. The in-degree of a vertex is the count of incoming directed edges. Vertices with in-degree 0 have no prerequisites and can execute immediately. Initialise a queue with all vertices having in-degree 0. Pop vertices, append them to the order, and decrement neighbours' in-degrees. When a neighbour's in-degree reaches 0, push it to the queue. If the final order contains fewer than V vertices, the graph contains a cycle.

Predict the output

Predict the in-degrees

Read the code and pick what it prints.

Round 1 of 2

What does this program print?

import java.util.*;
public class Main {
public static void main(String[] args) {
int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {0, 3}};
int[] inDegree = new int[4];
for (int[] e : edges) inDegree[e[1]]++;
System.out.println(Arrays.toString(inDegree));
}
}

DFS reverse postorder and three-colour cycle detection

DFS topological sort computes the order with depth-first search instead of in-degrees. Traverse the graph with DFS. When all descendants of vertex u finish, push u onto a result stack. Reversing this finishing order produces a valid topological sequence.

Java
// color: 0 = unvisited, 1 = exploring, 2 = finishedboolean dfs(int u, int[] color, Deque<Integer> stack) {    color[u] = 1;    for (int v : adj.get(u)) {        if (color[v] == 1) return false;                   // back edge: cycle        if (color[v] == 0 && !dfs(v, color, stack)) return false;    }    color[u] = 2;    stack.push(u);   // u finishes after all its descendants    return true;}

Cycle detection during DFS uses a three-state colouring scheme. State 0 represents unvisited, state 1 represents currently exploring, and state 2 represents fully finished. Visiting a neighbour in state 1 indicates a back edge, proving a cycle exists.

DFS topological sort runs in linear O(V + E) time. However, Kahn's algorithm is often preferred in interview settings. Kahn avoids recursive call stack overflow risk on deep linear dependency chains.

Course Schedule and build systems in production

The Course Schedule problem asks if students can complete all courses given prerequisite pairs. Each pair [a, b] represents a directed edge from b to a. Determining feasibility requires detecting whether the prerequisite graph contains a directed cycle.

Example 3 · Course Schedule II in Java

Main.javaJava
import java.util.*;
public class Main {    static int[] findOrder(int numCourses, int[][] prerequisites) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < numCourses; i++) adj.add(new ArrayList<>());        int[] inDegree = new int[numCourses];
        // edge from b -> a        for (int[] p : prerequisites) {            adj.get(p[1]).add(p[0]);            inDegree[p[0]]++;        }
        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < numCourses; i++) {            if (inDegree[i] == 0) q.offer(i);        }
        int[] order = new int[numCourses];        int count = 0;
        while (!q.isEmpty()) {            int curr = q.poll();            order[count++] = curr;
            for (int next : adj.get(curr)) {                inDegree[next]--;                if (inDegree[next] == 0) q.offer(next);            }        }
        return count == numCourses ? order : new int[0];    }
    public static void main(String[] args) {        int[][] prereqs = {{1, 0}, {2, 0}, {3, 1}, {3, 2}};        int[] order = findOrder(4, prereqs);        System.out.println("Course schedule: " + Arrays.toString(order));    }}
Output
Course schedule: [0, 1, 2, 3]

What this code does

  • Builds directed edge from prerequisite p[1] to target course p[0].
  • Queues initial courses with 0 prerequisites.
  • Returns ordered course plan or empty array if cycle prevents completion.

Example 4 · Task Ordering with Build Dependencies in Java

Main.javaJava
import java.util.*;
public class Main {    static boolean canFinishAll(int tasks, int[][] deps) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < tasks; i++) adj.add(new ArrayList<>());        int[] inDegree = new int[tasks];
        for (int[] d : deps) {            adj.get(d[1]).add(d[0]);            inDegree[d[0]]++;        }
        Queue<Integer> q = new LinkedList<>();        for (int i = 0; i < tasks; i++) {            if (inDegree[i] == 0) q.offer(i);        }
        int finished = 0;        while (!q.isEmpty()) {            int u = q.poll();            finished++;
            for (int v : adj.get(u)) {                inDegree[v]--;                if (inDegree[v] == 0) q.offer(v);            }        }
        return finished == tasks;    }
    public static void main(String[] args) {        int[][] validDeps = {{1, 0}, {2, 1}};        int[][] cyclicDeps = {{1, 0}, {0, 1}};        System.out.println("Valid pipeline can finish: " + canFinishAll(3, validDeps));        System.out.println("Cyclic pipeline can finish: " + canFinishAll(2, cyclicDeps));    }}
Output
Valid pipeline can finish: true
Cyclic pipeline can finish: false

What this code does

  • Valid pipeline finishes all 3 tasks in topological dependency order.
  • Cyclic dependency between 0 and 1 prevents queue insertion and returns false.
  • Cycle detection runs in linear O(V + E) time.

Build systems like Maven and Gradle rely fundamentally on topological sort. Each compilation target represents a vertex, and dependencies form directed edges. Topological ordering determines the exact sequence in which modules must be compiled. Independent vertices at the same level can be compiled concurrently across worker threads. Circular imports between software packages trigger cycle errors during build configuration. Resolving these cycles requires decoupling modules into separate interfaces.

Next step

Check your understanding

10 quick questions