AlgoFrames

Strongly connected components: Kosaraju and Tarjan

In a directed graph a strongly connected component is a set where every vertex reaches every other. Find them with Kosaraju’s or Tarjan’s algorithm.

Before you start: Prim's algorithm.

The idea

In a town of one-way streets, some groups of corners can all reach each other. Each such group is a strongly connected component.

Components show which parts of a road map, a call graph or a web of links can trap you in a loop.

Intuition

A, B and C lie on the cycle A → B → C → A. Each one reaches the other two, so they form one component.

B reaches D, but no edge path leads from D back to B. So D and E form a separate component, and F is alone.

Shrink each component to one node. The result has no cycle: it is a DAG, the condensation.

A cycle between two components would let their nodes reach each other, so they would be one component.

Complexity

Each pass visits every node and edge once, and so does building the reversed graph. Time is O(V + E).

The stack and the flags take O(V) space. Kosaraju also stores the reversed edges, which adds O(E).

Pitfalls

Pass 2 must search the reversed graph. In the original graph A reaches every node, so all six would merge into one wrong component.

On a long chain, recursive DFS keeps one call open per node. Large graphs can overflow the call stack, so use an explicit stack there.

Python stops at about 1,000 nested calls by default. A chain of 100,000 nodes needs 100,000.

Variations

Tarjan finds the same components in one DFS. Each label is disc/low, and a node with low = disc is the root of a component.

low is the earliest entry time reachable through the subtree and one edge back to a node still on the stack.

Kosaraju finds components in topological order of the condensation. Component 1 has no incoming edge from the others.

Code

Pseudocode

order ← empty stack, seen ← {}
for each node s: if s not seen: dfs1(s)
dfs1(u):
  add u to seen
  for each edge u → v: if v not seen: dfs1(v)
  push u onto order
R ← the graph with every edge reversed
comp[all] ← none, k ← 0
while order not empty
  u ← pop order
  if comp[u] = none
    k ← k + 1; mark all nodes u reaches in R as k
return k

Python

def kosaraju(n, edges):
    out = [[] for _ in range(n)]
    rev = [[] for _ in range(n)]
    for u, v in edges:
        out[u].append(v)
        rev[v].append(u)
    seen, order = [False] * n, []
    def dfs1(u):
        seen[u] = True
        for v in out[u]:
            if not seen[v]:
                dfs1(v)
        order.append(u)
    for s in range(n):
        if not seen[s]:
            dfs1(s)
    comp, k = [-1] * n, 0
    for u in reversed(order):
        if comp[u] < 0:
            stack, comp[u] = [u], k
            while stack:
                x = stack.pop()
                for y in rev[x]:
                    if comp[y] < 0:
                        comp[y] = k
                        stack.append(y)
            k += 1
    return k

JavaScript

function kosaraju(n, edges) {
  const out = Array.from({ length: n }, () => []);
  const rev = Array.from({ length: n }, () => []);
  for (const [u, v] of edges) {
    out[u].push(v);
    rev[v].push(u);
  }
  const seen = new Array(n).fill(false), order = [];
  function dfs1(u) {
    seen[u] = true;
    for (const v of out[u]) if (!seen[v]) dfs1(v);
    order.push(u);
  }
  for (let s = 0; s < n; s++) if (!seen[s]) dfs1(s);
  const comp = new Array(n).fill(-1);
  let k = 0;
  for (let i = order.length - 1; i >= 0; i--) {
    if (comp[order[i]] >= 0) continue;
    const stack = [order[i]];
    comp[order[i]] = k;
    while (stack.length > 0) {
      const x = stack.pop();
      for (const y of rev[x]) if (comp[y] < 0) { comp[y] = k; stack.push(y); }
    }
    k++;
  }
  return k;
}

Java

int kosaraju(int n, int[][] edges) {
    List<List<Integer>> out = new ArrayList<>(), rev = new ArrayList<>();
    for (int i = 0; i < n; i++) { out.add(new ArrayList<>()); rev.add(new ArrayList<>()); }
    for (int[] e : edges) { out.get(e[0]).add(e[1]); rev.get(e[1]).add(e[0]); }
    boolean[] seen = new boolean[n];
    Deque<Integer> order = new ArrayDeque<>();
    for (int s = 0; s < n; s++) if (!seen[s]) dfs1(s, out, seen, order);
    int[] comp = new int[n];
    Arrays.fill(comp, -1);
    int k = 0;
    while (!order.isEmpty()) {
        int u = order.pop();
        if (comp[u] >= 0) continue;
        Deque<Integer> stack = new ArrayDeque<>(List.of(u));
        comp[u] = k;
        while (!stack.isEmpty()) {
            int x = stack.pop();
            for (int y : rev.get(x)) if (comp[y] < 0) { comp[y] = k; stack.push(y); }
        }
        k++;
    }
    return k;
}

void dfs1(int u, List<List<Integer>> out, boolean[] seen, Deque<Integer> order) {
    seen[u] = true;
    for (int v : out.get(u)) if (!seen[v]) dfs1(v, out, seen, order);
    order.push(u);
}

Cost at a glance

TimeO(V + E)
SpaceO(V)
InputDirected graph
OutputStrongly connected components

Practice problems (5)

Spot a component Warm-up

Which set of nodes is exactly one strongly connected component of this directed graph?

Low-link values Warm-up

Follow Tarjan's algorithm from A. Each node shows disc/low: its entry time and the earliest entry time it can reach back to. Type each low value before the step plays.

Finishing order Standard

Pass 1 of Kosaraju runs DFS from A and records when each node finishes. After each finish, click the node that finishes next.

Count SCCs Standard

Return the number of strongly connected components of a directed graph. Two nodes are in the same component when each can reach the other.

graph.n is the node count and graph.edges lists [u, v] pairs for edges u → v. Edges may repeat, and self-loops can appear.

Condensation graph Standard

Shrink every strongly connected component of a directed graph to one node. Name each component by its smallest node number.

Return the edges of this condensation graph as [a, b] pairs of component names. List each pair once, in any order. Edges inside one component disappear.

Next on the path: Maximum flow: Ford-Fulkerson and Edmonds-Karp