Graphs · Pattern 8 of 14

Topological sort: an order that respects every dependency

Count how many edges point into each node. Nodes with none can go first; removing them frees their neighbours. If some nodes never reach zero, there is a cycle and no valid order.

4 variations · 12 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Tasks, courses or recipes with prerequisites
  • Find any order that respects every "a before b" rule, or say none exists
  • The longest chain, or the number of rounds when independent tasks run in parallel
  • Peel a tree from its leaves inwards

The template

Topological Sort
// Kahn's algorithm. Edge [u, v]: u must come before v. Empty result: there is a cycle.
int[] topoSort(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    int[] indeg = new int[n];
    for (int[] e : edges) { adj.get(e[0]).add(e[1]); indeg[e[1]]++; }
    Deque<Integer> q = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);   // nothing to wait for
    int[] order = new int[n];
    int k = 0;
    while (!q.isEmpty()) {
        int u = q.poll();
        order[k++] = u;
        for (int v : adj.get(u)) if (--indeg[v] == 0) q.offer(v);  // v's last prerequisite is done
    }
    return k == n ? order : new int[0];
}

// peel leaves layer by layer: the last 1 or 2 nodes are the centres of the tree
int[] findMinHeightTrees(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    int[] deg = new int[n];
    for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); deg[e[0]]++; deg[e[1]]++; }
    Deque<Integer> leaves = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (deg[i] <= 1) leaves.offer(i);
    for (int left = n; left > 2; ) {
        left -= leaves.size();
        for (int size = leaves.size(); size > 0; size--) {
            int u = leaves.poll();
            for (int v : adj.get(u)) if (--deg[v] == 1) leaves.offer(v);
        }
    }
    return leaves.stream().mapToInt(Integer::intValue).toArray();
}

The variations

  1. 1Kahn's algorithm: order the tasks

    Start with every node of in-degree 0. Each time you take one, lower its neighbours' in-degree and queue the ones that reach 0. "Can all courses finish?" is just "did all n nodes come out?".

  2. 2Build the graph first

    The edges are hidden in the input. Compare neighbouring words: the first letter where they differ gives one edge. A recipe depends on each of its ingredients; supplies are the starting nodes.

  3. 3DP along the topological order

    Process nodes in topological order and push a value to each neighbour: the earliest semester or finish time (longest path), or the quietest richer person. In a grid, "strictly increasing" makes the edges acyclic, so the longest increasing path is a DP over the same order.

  4. 4Peel a tree from its leaves

    The same in-degree idea on a tree: remove all leaves (degree 1), then the new leaves, layer by layer. The last 1 or 2 nodes are the centres. Coinless leaves can be trimmed the same way before trimming two more layers.

Mistakes to avoid

  • Getting the edge direction backwards: for [course, prereq] the edge goes prereq → course.
  • Returning the partial order when there is a cycle. Always check that every node made it into the order.
  • Alien dictionary: when a word is followed by its own prefix (like "abc" before "ab"), the order is invalid. Also add every letter as a node, even ones with no edges.
Next: Dijkstra's algorithm: shortest paths with weights →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.