Topological Sort & Strongly Connected Components

Order tasks that depend on each other, and find the groups of vertices that can all reach one another.

Advanced 3 min readLesson 14 of 18 Interview Q&A

Topological sort

A topological order of a directed graph lists the vertices so that every edge u → v has u before v. It exists if and only if the graph is a DAG (no directed cycles). It's how build systems order compilation, package managers install dependencies, spreadsheets recalculate cells, schedulers order jobs and course planners order prerequisites.

MathProgDSAAlgoOS
One valid order: Math, Prog, DSA, Algo, OS (also Prog, Math, DSA, OS, Algo).

Kahn's algorithm (BFS on in-degrees)

Repeatedly output a vertex with in-degree 0 (no remaining prerequisites) and remove its outgoing edges. If some vertices are never output, there's a cycle.

int[] topoSort(int n, int[][] edges) {        // edge {u, v}: u before v
    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);
    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];       // empty → cycle detected
}

DFS-based topological sort

Run DFS; when a vertex finishes (all descendants done), push it onto a list. Reverse post-order is a topological order. Combine with three-colour cycle detection.

Both are O(V + E). Kahn's is often easier to reason about and naturally detects cycles; it also lets you process levels (all courses you can take this semester) and pick the lexicographically smallest order with a min-heap instead of a queue.

Shortest/longest paths in a DAG

Process vertices in topological order and relax outgoing edges: shortest paths in O(V + E), even with negative weights. Negate weights to get the longest path — the critical path in project scheduling.

Strongly connected components (SCC)

In a directed graph, an SCC is a maximal set of vertices where every vertex can reach every other. Collapsing each SCC into one node yields a DAG (the condensation).

abcdef
Three SCCs: {a, b, c}, {d, e}, {f}.

Kosaraju's algorithm

  1. DFS the graph and record vertices by finishing time.
  2. Reverse every edge.
  3. DFS the reversed graph in decreasing finish order; each DFS tree is one SCC.

Tarjan's algorithm

One DFS that tracks each vertex's discovery index and low-link (the smallest index reachable from its subtree through back edges). When low[u] == index[u], pop the stack down to u — that's an SCC. Also O(V + E).

Kosaraju
List<List<Integer>> scc(List<List<Integer>> adj) {
    int n = adj.size();
    boolean[] seen = new boolean[n];
    Deque<Integer> order = new ArrayDeque<>();
    for (int i = 0; i < n; i++) if (!seen[i]) dfs1(i, adj, seen, order);
    List<List<Integer>> radj = new ArrayList<>();
    for (int i = 0; i < n; i++) radj.add(new ArrayList<>());
    for (int u = 0; u < n; u++) for (int v : adj.get(u)) radj.get(v).add(u);
    Arrays.fill(seen, false);
    List<List<Integer>> comps = new ArrayList<>();
    while (!order.isEmpty()) {
        int u = order.pop();
        if (seen[u]) continue;
        List<Integer> comp = new ArrayList<>();
        dfs2(u, radj, seen, comp);
        comps.add(comp);
    }
    return comps;
}
void dfs1(int u, List<List<Integer>> g, boolean[] seen, Deque<Integer> order) {
    seen[u] = true;
    for (int v : g.get(u)) if (!seen[v]) dfs1(v, g, seen, order);
    order.push(u);                               // push on finish
}
void dfs2(int u, List<List<Integer>> g, boolean[] seen, List<Integer> comp) {
    seen[u] = true; comp.add(u);
    for (int v : g.get(u)) if (!seen[v]) dfs2(v, g, seen, comp);
}

Uses: finding mutually dependent modules, 2-SAT solving, analysing web/social graphs, and deadlock detection in wait-for graphs.

Key takeaways
  • A topological order exists iff the graph is a DAG.
  • Kahn's (in-degree BFS) and DFS post-order both run in O(V + E) and detect cycles.
  • DAG shortest/longest paths: relax edges in topological order.
  • SCCs: Kosaraju (two DFS passes, one on the reversed graph) or Tarjan (one pass with low-links).
Interview questions
QAlien dictionary: given words sorted in an unknown alphabet, find the letter order.hard

Compare each adjacent pair of words; the first differing characters give an edge c1 → c2. (If a word is longer than the next one and has it as a prefix, the input is invalid.) Topologically sort the letters; a cycle means no valid order.

QFind all critical connections (bridges) in a network.hard

Tarjan's bridge-finding: DFS assigning discovery times and low-links; edge (u, v) is a bridge if low[v] > disc[u] — v's subtree can't reach u or above except through that edge. O(V + E).