Strongly Connected Components (Kosaraju)
Strongly Connected Components (Kosaraju) is a GFG problem (Medium). You get a directed graph with V vertices numbered 0 to V − 1 and a list edges, where [u, v] is an edge from u to v. Return the number of strongly connected components.
- A strongly connected component (SCC) is a largest group of vertices in which every vertex can reach every other one by following edges forward.
- Every vertex is in exactly one component. A vertex that lies on no cycle is a component on its own.
Both V and E go up to 10⁶, so the count must take O(V + E) time, and a recursive DFS would run out of stack on a long chain of vertices.
- 1 <= V <= 10⁶
- 0 <= E <= 10⁶
- 0 <= edges[i][0], edges[i][1] < V
Intuition
A DFS started inside a component that has no edge leaving it reaches exactly that component. Kosaraju's algorithm for SCCs finds such components one by one:
- Pass 1, finish order: run DFS on the graph and note when each vertex finishes. The vertex that finishes last sits in a component that no other component points into.
- Pass 2, reversed edges: reversing every edge keeps each component the same but leaves that component with no way out, so a DFS from it marks exactly one component. The next unmarked vertex in finish order repeats the trick: its reversed edges can only leave into components already marked.
"Groups where everyone can reach everyone" in a directed graph is a strongly connected component problem. Two-way reachability is the tell: in an undirected graph plain connected components would do, but one-way edges need the two passes.
Approach
Before reading on, take a graph with two cycles joined by one edge and ask where a DFS started in each cycle would end up. Then think about which cycle you would want to start from, and whether reversing the edges helps. Aim for O(V + E).
Build the graph and its reverse
For each edge [u, v], add v to adj[u] and u to radj[v]. Building both lists in one loop means the reversed graph is ready for the second pass without another scan of the edges.
Pass 1: record the finish order
From every unvisited vertex, run DFS on adj with an explicit stack and a pointer it[v] to the next neighbour to try. When v has no neighbours left, pop it and append it to order. A vertex is recorded only after everything reachable from it, which is what makes the last vertex in order a safe place to start.
Pass 2: walk the order from the end
Go through order from the last vertex to the first. A vertex that is still unmarked belongs to a component nobody has found yet, so add 1 to the count and start a search from it.
Mark everything reachable on reversed edges
Use a plain stack on radj and mark every vertex you reach. The search stays inside one component: any reversed edge that leaves it points into a component that was started earlier in this pass, and those vertices are already marked.
Return the count
Each vertex is marked once in pass 2, so after the loop the count equals the number of strongly connected components. To list the components instead, collect the vertices each search marks.
Code in Python, C++ and Java
Common pitfalls
Recursive DFS on a long chain
def dfs(v):
seen[v] = True
for u in adj[v]:
if not seen[u]:
dfs(u)
order.append(v)stack = [s]
while stack:
v = stack[-1]
if it[v] < len(adj[v]):
...
else:
stack.pop()
order.append(v)With edges 0 → 1 → 2 → … → 10⁵ the recursion goes 10⁵ calls deep. Python stops at about 1,000 with RecursionError, and C++ and Java can overflow their call stacks well before 10⁶. The explicit stack with a next-neighbour pointer gives the same finish order with no depth limit.
Recording a vertex when it is first visited
seen[u] = True order.append(u) stack.append(u)
else:
stack.pop()
order.append(v)The proof needs finish order. With V = 2 and edges = [[0, 1]], visit order is [0, 1], so pass 2 starts from 1, follows the reversed edge to 0 and counts one component. The answer is 2: 0 and 1 cannot reach each other both ways.
Walking the finish order from the front
for s in order:
for s in reversed(order):
The first vertex to finish sits in a component that other components point into, so on reversed edges it can escape. With edges = [[0, 1]] the order is [1, 0]; starting at 1 reaches 0 and the code returns 1 instead of 2.
Searching the original edges in pass 2
for u in adj[v]:
for u in radj[v]:
Forward edges lead out of the component the search starts in. With edges = [[0, 1]] pass 2 starts at 0, follows 0 → 1 and merges two components into one.
Edge cases
V = 3, edges = []Every vertex finishes alone in pass 1 and starts its own search in pass 2, so the count is V, here 3.
Pass 1 loops over every vertex as a possible start, so a vertex with no path from 0 still gets a finish time and is counted.
[2, 2]Vertex 2 is already marked when its own edge is checked, so the loop changes nothing and 2 is still one component.
Complexity
Strongly Connected Components (Kosaraju) FAQ
Why does the vertex that finishes last lie in a component nothing points into?
Take an edge from component C to component D. If the DFS enters C first, it reaches all of D before it can leave C, so C's last finish is later. If it enters D first, it cannot reach C (or C and D would be one component), so all of D finishes before C even starts. Either way C finishes after D, so the overall last finisher has no component pointing into it.
Kosaraju or Tarjan: which should I use?
Both run in O(V + E). Tarjan's algorithm needs one DFS and no reversed graph, using a low-link value per vertex to spot where a component ends. Kosaraju's two passes are easier to explain and to get right in an interview, and the reversed graph costs only one extra list per vertex.
Does pass 2 have to be a DFS?
No. Pass 2 only needs to mark everything reachable on the reversed edges, so a BFS or any stack order works. Only pass 1 must be a true DFS, because it depends on finish times.