Kosaraju's Algorithm
–
Pseudocode
1// pass 1: DFS on the original graph2for each vertex v that is not visited: dfs1(v)3 dfs1(u): visit u, call dfs1 on unvisited out-neighbours, then push u on a stack4// pass 2: reverse every edge5while the stack is not empty: v ← pop6 if v has no component yet: dfs2(v) on the reversed graph7 every vertex dfs2 reaches is one strongly connected component
Pass
0
Components
0
stackfinished in pass 1 (yellow)being exploredcolourone strongly connected component
What is Kosaraju's Algorithm?
In a directed graph, a strongly connected component (SCC) is a group of vertices where each one can reach every other one by following the arrows. Squashing every SCC into a single vertex leaves a graph with no cycles.
Kosaraju's algorithm finds them with two depth-first searches. The first records the order in which vertices finish. The second runs on the graph with every edge reversed, starting from the vertices that finished last. Each search in the second pass stays trapped inside exactly one SCC.
DFS for finish order, then DFS the reversed graph in reverse finish order.
Using the Visualizer
- • Pass 1: blue = visited, yellow = finished and pushed on the stack shown on the right.
- • Pass 2 flips every arrow on the board ("showing the REVERSED graph") and pops the stack.
- • Each colour is one strongly connected component.
- • Compare with Tarjan's algorithm, which finds the same components in one pass.
How It Works
1. First DFS
Explore everything; push each vertex on a stack when it finishes.
2. Reverse the edges
Every u → v becomes v → u.
3. Pop and explore
Pop a vertex without a component and DFS the reversed graph from it.
4. One search, one SCC
Everything that search reaches is one strongly connected component.
Implementation
Properties & Complexity
Time Complexity
- • Two DFS passes: O(V + E) with adjacency lists
- • Reversing the graph: O(V + E)
Space & Properties
- • Space: O(V + E) for the reversed graph and the stack
- • Output order: SCCs come out in topological order
Where It Is Used
- • Condensing a graph into a DAG of components
- • 2-SAT solving
- • Finding cycles of dependencies in software modules
- • Web graphs: groups of pages that all link to each other
Limitations
- • Two passes and a reversed copy of the graph (Tarjan needs neither)
- • Recursion depth can overflow on very long paths