Kosaraju's Algorithm (Strongly Connected Components)

hard

Given a directed graph with V vertices (0 .. V-1) and directed edges edges, return the number of strongly connected components (SCCs) — maximal groups of vertices in which every vertex can reach every other.

Hints

An SCC is a maximal set where every vertex reaches every other (directed).
Kosaraju: DFS by finish time, then DFS the transpose in reverse order.
Tarjan: one DFS with discovery times and low-links; an SCC root has low[u] == disc[u].

Common doubts

Processing the transpose in reverse finish order guarantees each DFS tree stays within one SCC, so the tree count equals the SCC count.
The smallest discovery time reachable from u's subtree using tree edges and one back edge to a vertex still on the stack.
Both are O(V+E). Tarjan needs a single pass and no transpose; Kosaraju is often considered simpler to reason about.

Interview follow-ups

Collect the vertices of each transpose DFS tree (Kosaraju) or each popped stack segment (Tarjan).
Contract each SCC to a single node; the result is always a DAG.

Fun facts

  • Tarjan's SCC algorithm (1972) was among the first to exploit DFS low-links — the same idea behind bridges and articulation points.
  • The condensation of any directed graph into SCCs is a DAG, which is why 2-SAT reduces to SCCs.

Asked at

GoogleAmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 5, edges = [[0,1],[1,2],[2,0],[1,3],[3,4]]
Output: 3
{0,1,2} is one SCC; {3} and {4} are singletons.
Example 2
Input: V = 3, edges = [[0,1],[1,2],[2,0]]
Output: 1
The whole cycle is one strongly connected component.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - edges are directed u -> v - no duplicate edges

Solve this problem →