Strongly connected components
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Strongly connected components partition directed graphs into maximal mutually reachable subgraphs in linear O(V + E) time.
Strong connectivity and Kosaraju two-pass algorithm
In a directed graph, a component is strongly connected if every vertex can reach every other vertex. A Strongly Connected Component (SCC) is a maximal subset with this mutual reachability property.
Brute force search runs DFS from every vertex to every other vertex, taking O(V * (V + E)) time.
Kosaraju two-pass SCC discovery
Step 1 of 3
- stackTop
- A
- sccCount
- 0
Example 1 · Brute force: reachability from every vertex, O(V * (V + E))
import java.util.*;
public class Main { static void dfs(int u, List<List<Integer>> adj, boolean[] seen) { seen[u] = true; for (int v : adj.get(u)) { if (!seen[v]) dfs(v, adj, seen); } }
public static void main(String[] args) { int n = 4; int[][] edges = {{0, 1}, {1, 0}, {1, 2}, {2, 3}, {3, 2}}; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int[] e : edges) adj.get(e[0]).add(e[1]);
boolean[][] reach = new boolean[n][n]; for (int i = 0; i < n; i++) dfs(i, adj, reach[i]); // one full DFS per vertex
boolean[] assigned = new boolean[n]; List<List<Integer>> sccs = new ArrayList<>(); for (int i = 0; i < n; i++) { if (assigned[i]) continue; List<Integer> comp = new ArrayList<>(); for (int j = 0; j < n; j++) { if (reach[i][j] && reach[j][i]) { // reach each other both ways comp.add(j); assigned[j] = true; } } sccs.add(comp); } System.out.println("Total SCCs: " + sccs.size()); for (List<Integer> comp : sccs) System.out.println("SCC: " + comp); }}Total SCCs: 2 SCC: [0, 1] SCC: [2, 3]
What this code does
- A DFS from every vertex builds a table: can i reach j?
- Two vertices are in the same component exactly when each can reach the other.
- The table costs V searches, and it needs V * V memory; Kosaraju uses just two passes.
Example 2 · Optimal: Kosaraju two passes, O(V + E) time
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;
public class KosarajuDemo { public static List<List<Integer>> findSCCs(int n, int[][] edges) { List<List<Integer>> adj = new ArrayList<>(); List<List<Integer>> rev = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); rev.add(new ArrayList<>()); } for (int[] e : edges) { adj.get(e[0]).add(e[1]); rev.get(e[1]).add(e[0]); }
Deque<Integer> stack = new ArrayDeque<>(); boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) { if (!visited[i]) dfs1(i, adj, visited, stack); }
List<List<Integer>> sccs = new ArrayList<>(); boolean[] visitedRev = new boolean[n]; while (!stack.isEmpty()) { int u = stack.pop(); if (!visitedRev[u]) { List<Integer> comp = new ArrayList<>(); dfs2(u, rev, visitedRev, comp); sccs.add(comp); } } return sccs; }
private static void dfs1(int u, List<List<Integer>> adj, boolean[] vis, Deque<Integer> st) { vis[u] = true; for (int v : adj.get(u)) { if (!vis[v]) dfs1(v, adj, vis, st); } st.push(u); }
private static void dfs2(int u, List<List<Integer>> rev, boolean[] vis, List<Integer> comp) { vis[u] = true; comp.add(u); for (int v : rev.get(u)) { if (!vis[v]) dfs2(v, rev, vis, comp); } }
public static void main(String[] args) { int n = 4; // edges: 0->1, 1->0, 1->2, 2->3, 3->2 int[][] edges = {{0, 1}, {1, 0}, {1, 2}, {2, 3}, {3, 2}}; List<List<Integer>> sccs = findSCCs(n, edges); System.out.println("Total SCCs: " + sccs.size()); for (List<Integer> comp : sccs) System.out.println("SCC: " + comp); }}Total SCCs: 2 SCC: [0, 1] SCC: [2, 3]
What this code does
- Runs first DFS pass to push vertices onto stack ordered by finish time.
- Traverses reversed graph popping from stack to isolate each mutually reachable component.
- Identifies 2 separate components: {0, 1} and {2, 3} linked by one-way bridge 1->2.
- Two DFS passes replace the V searches and the V * V table, because finish order already separates the components.
Kosaraju's algorithm finds all SCCs in linear O(V + E) time using two DFS passes. Pass 1 performs a standard DFS on the original graph, pushing vertices onto a stack by finish time. Pass 2 reverses the direction of all edges to form the transposed graph. Popping vertices from the stack and running DFS on the transposed graph extracts each SCC.
Consider four vertices where A and B form a cycle, and C and D form another cycle. A directed bridge edge connects B to C. Pass 1 finishes exploring C and D before popping back to finish A and B. Pass 2 traverses transposed edges starting from A, preventing reachability from escaping into C.
Order of execution
Run Kosaraju
Tap the steps of Kosaraju's algorithm in order.
Tarjan algorithm using discovery times and low-link values
Tarjan's algorithm achieves SCC decomposition in a single DFS pass in O(V + E) time. It assigns each visited vertex an incrementing discovery time tin[u]. It maintains low[u], representing the lowest discovery time reachable via tree and back edges.
Example 3 · Tarjan Single-Pass SCC Algorithm
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;
public class TarjanSCCDemo { private static int timer;
public static List<List<Integer>> tarjanSCC(int n, int[][] edges) { List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int[] e : edges) adj.get(e[0]).add(e[1]);
int[] tin = new int[n]; int[] low = new int[n]; boolean[] onStack = new boolean[n]; Deque<Integer> stack = new ArrayDeque<>(); List<List<Integer>> sccs = new ArrayList<>(); timer = 0;
for (int i = 0; i < n; i++) { if (tin[i] == 0) dfs(i, adj, tin, low, onStack, stack, sccs); } return sccs; }
private static void dfs(int u, List<List<Integer>> adj, int[] tin, int[] low, boolean[] onStack, Deque<Integer> stack, List<List<Integer>> sccs) { tin[u] = low[u] = ++timer; stack.push(u); onStack[u] = true;
for (int v : adj.get(u)) { if (tin[v] == 0) { dfs(v, adj, tin, low, onStack, stack, sccs); low[u] = Math.min(low[u], low[v]); } else if (onStack[v]) { low[u] = Math.min(low[u], tin[v]); } }
if (low[u] == tin[u]) { List<Integer> comp = new ArrayList<>(); while (true) { int node = stack.pop(); onStack[node] = false; comp.add(node); if (node == u) break; } sccs.add(comp); } }
public static void main(String[] args) { int n = 4; int[][] edges = {{0, 1}, {1, 0}, {1, 2}, {2, 3}, {3, 2}}; List<List<Integer>> sccs = tarjanSCC(n, edges); System.out.println("SCCs found by Tarjan: " + sccs.size()); }}SCCs found by Tarjan: 2
What this code does
- Assigns discovery times tin[u] and maintains low-link values low[u] in a single DFS pass.
- When low[u] == tin[u], pops stack elements until u to extract the entire SCC.
- Finds both strongly connected components in optimal linear O(V + E) time.
Vertices are pushed onto a recursion stack as they are visited. When exploring neighbour v, if v is already on the stack, low[u] updates to min(low[u], tin[v]). If low[u] == tin[u] after exploring all neighbours, u is the root of an SCC. To extract the component, pop vertices from the stack until u itself is popped. All popped vertices form a complete strongly connected component. Tarjan's method requires only one graph traversal and avoids building the transposed graph.
The condensation graph: turning cyclic graphs into a DAG
In many real-world applications, cyclic dependencies obstruct optimisation. The condensation graph contracts each SCC into a single composite super-vertex. A directed edge connects super-vertex C1 to C2 if any edge goes from C1 to C2.
Example 4 · Condensation DAG Construction
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class CondensationDAGDemo { public static void main(String[] args) { int n = 4; // Two SCCs: Component 0 has {0, 1}, Component 1 has {2, 3} int[] sccId = {0, 0, 1, 1}; int sccCount = 2;
int[][] edges = {{0, 1}, {1, 0}, {1, 2}, {2, 3}, {3, 2}}; List<Set<Integer>> dag = new ArrayList<>(); for (int i = 0; i < sccCount; i++) dag.add(new HashSet<>());
for (int[] e : edges) { int u = e[0], v = e[1]; if (sccId[u] != sccId[v]) { dag.get(sccId[u]).add(sccId[v]); } }
System.out.println("Super-node 0 points to: " + dag.get(0)); System.out.println("Super-node 1 points to: " + dag.get(1)); }}Super-node 0 points to: [1] Super-node 1 points to: []
What this code does
- Maps each original vertex to its containing SCC component identifier.
- Adds directed edges between differing component IDs to build the condensation network.
- Produces an acyclic DAG where super-node 0 points to 1 with zero cycles.
The resulting condensation graph is guaranteed to be a Directed Acyclic Graph (DAG). If a cycle existed between super-vertices, all involved SCCs would collapse into one larger SCC. This guarantees the absence of cycles among composite components. Transforming an arbitrary directed graph into a DAG unlocks powerful techniques. You can now compute topological sorts, shortest paths, and dynamic programming. Problems like finding the maximum coins collected on directed networks rely on this condensation.
Next step
Check your understanding
10 quick questions