Topological Sort Pattern

Order things with dependencies — course schedules, build orders, alien dictionaries — with Kahn's in-degree BFS.

Intermediate 2 min readLesson 14 of 25

Whenever items have "must come before" relationships, you have a directed graph, and a valid ordering is a topological sort. If the dependencies contain a cycle, no valid order exists — detecting that is often the actual question. (Theory and the DFS approach: Topological sort & SCC.)

0123
Prerequisites: 0 before 1 and 2; both before 3. Orders: 0,1,2,3 or 0,2,1,3.
When to use this pattern
  • Tasks / courses / packages with prerequisites or dependencies.
  • "Is it possible to finish all…?" (cycle detection) or "return an order".
  • Deriving an ordering from pairwise comparisons (alien dictionary, sequence reconstruction).
  • Processing in "rounds" where each round handles everything currently unblocked (parallel courses → number of semesters).

Template: Kahn's algorithm

  1. Build the adjacency list and the in-degree of every node.
  2. Queue every node with in-degree 0 (no prerequisites).
  3. Pop a node, append it to the order, and decrement its neighbours' in-degrees; queue any that reach 0.
  4. If the order contains every node, it's valid; otherwise there's a cycle.
Course Schedule II
int[] findOrder(int n, int[][] prereq) {          // prereq {a, b}: take b before a
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    int[] indeg = new int[n];
    for (int[] p : prereq) { adj.get(p[1]).add(p[0]); indeg[p[0]]++; }

    Deque<Integer> q = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i);
    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);
    }
    return k == n ? order : new int[0];           // cycle → impossible
}

Variations

ProblemTwist
Course Schedule IOnly return whether k == n
Parallel Courses (min semesters)Process the queue level by level; count levels
Alien DictionaryBuild edges from the first differing letter of adjacent words
Smallest lexicographic orderUse a min-heap instead of a queue
Unique order? (Sequence Reconstruction)The queue must never hold more than one node
Minimum height treesPeel leaves (degree 1) layer by layer from an undirected tree
Longest path in a DAG / critical pathRelax distances in topological order
Practice problems
  • Course Schedulecycle detectionmedium
  • Course Schedule IImedium
  • Find All Possible Recipes from Given Suppliesmedium
  • Minimum Height Treespeel leavesmedium
  • Parallel Coursescount BFS levelsmedium
  • Sequence Reconstructionqueue size must be 1medium
  • Alien Dictionaryhard
  • Longest Increasing Path in a Matrixtopological order by value or memo DFShard
Key takeaways
  • Dependencies ⇒ directed graph ⇒ topological sort.
  • Kahn's: start from in-degree 0, peel layers; leftover nodes mean a cycle.
  • Get the edge direction right.
  • Level-by-level processing counts rounds; a min-heap gives the lexicographically smallest order.