Kosaraju
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Kosaraju's method finds strongly connected groups with two simple walks: one to note the finishing order, and a second on the reversed arrows that peels off one group at a time. It is easy to remember and easy to code.
Practical use cases
- Web app: Finding circular imports in a front-end project. A React project has files importing each other. A script walks the import graph once to get the finishing order, reverses imports, and walks again to print each tangle. Developers get a list like "these 5 files import each other".
- Web app: Link audit for a big website. A content team wants to know which sections of a 10,000-page site are closed loops. The audit labels each loop group and counts pages that cannot reach the rest of the site, giving editors a to-do list. Each loop group becomes one line in the report, and editors can fix them by adding a link out to the main menu.
- Web app: Checking permission rule loops. An access system where roles can grant other roles can form rings. Grouping rings shows that all roles in a ring in effect have the same rights, so the admin can merge them.
- System: 2-SAT solvers and network analysis. Logic solvers for simple yes or no rules use this grouping to decide if rules conflict, and network analysts use it to separate the dense core from the rest.
The story: Raju Drives Backwards
Raju the rickshaw driver was tired of one-way streets. "I want to know which junction groups I can freely move around in and return from," he told Mira. She had learned the DFS finishing-order trick from the topological sort lesson, and she was excited to use it again.
"Step one: wander around the map with a DFS and keep a note of the order in which junctions finish, meaning you have explored everything beyond them. The junctions that finish last are the ones at the very start of the chain of families."
"Step two, the magic: turn every arrow around. A family stays a family, because a loop reversed is still a loop. But the roads leading from one family to another now point backwards, so they become walls! Start from the last-finished junction and explore on the reversed map. You are trapped inside its own family, and exactly that family is what you discover. Cross it off, pick the next last-finished junction, repeat."
Raju named it after the Indian-born computer scientist S. Rao Kosaraju, who described it. In short: DFS, flip all arrows, DFS again in reverse finishing order. Each second-pass search tree is one strongly connected component.
How to spot this problem, and where you need it
You need to split a directed network into mutually reachable groups, and you prefer a clear, easy-to-reason-about method over a clever single-pass one.
Signs you need it
- The data has one-way arrows and you need groups where every item can get back to every other.
- You can easily build the reversed network, for example the "imported by" list next to the "imports" list.
- Interview or contest wording asks for "strongly connected components" and mentions reversing edges.
Where to use it in a project
- Static analysis scripts for imports, services or call graphs.
- Reports on tangled permissions, workflows or page links where you need clear named groups.
The solution
Step one: run DFS over the whole graph and push each node on a stack when it finishes. Step two: reverse every arrow. Step three: pop nodes from the stack; for each node not yet visited, run DFS on the reversed graph. Everything that DFS reaches forms one strongly connected group. Repeat until the stack is empty. The finishing order guarantees each run stays inside its own group.
Payoff: Before: manual hunting through 300 files for loops. After: two passes list every tangle, with the files in each.
Explain it like I am 8
First wander through the town and write down who you finished exploring last. Then turn all the one-way signs around. Start from whoever you wrote last and walk: the only place you can reach is your own gang, because the signs that used to lead out now point back at you.
How it works, step by step
- Pass 1: run DFS on the original graph. When a node finishes, push it onto a
finishlist. - Reverse every edge to build the transposed graph.
- Pass 2: go through the
finishlist from the last to the first. For an unvisited node, run DFS on the reversed graph. - Everything that DFS reaches is one strongly connected component. Give it a new number.
- Repeat for the next unvisited node in the list until all nodes are assigned.
The code in four languages
PHP
<?php
// Kosaraju: returns the strongly connected components
function kosaraju(int $n, array $edges): array {
$adj = array_fill(0, $n, []);
$radj = array_fill(0, $n, []); // the same roads, arrows flipped
foreach ($edges as [$a, $b]) { $adj[$a][] = $b; $radj[$b][] = $a; }
// Pass 1: remember the order in which nodes finish
$seen = array_fill(0, $n, false);
$finish = [];
$dfs1 = function (int $u) use (&$dfs1, &$seen, &$finish, $adj): void {
$seen[$u] = true;
foreach ($adj[$u] as $v) if (!$seen[$v]) $dfs1($v);
$finish[] = $u;
};
for ($i = 0; $i < $n; $i++) if (!$seen[$i]) $dfs1($i);
// Pass 2: on the flipped graph, start from the last-finished node
$comp = array_fill(0, $n, -1);
$groups = [];
$dfs2 = function (int $u, int $id) use (&$dfs2, &$comp, &$groups, $radj): void {
$comp[$u] = $id;
$groups[$id][] = $u;
foreach ($radj[$u] as $v) if ($comp[$v] < 0) $dfs2($v, $id);
};
$count = 0;
for ($k = $n - 1; $k >= 0; $k--) {
$u = $finish[$k];
if ($comp[$u] < 0) $dfs2($u, $count++);
}
foreach ($groups as &$g) sort($g); // tidy output
return $groups;
}
// junctions 1..6 become 0..5
$roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,3],[4,5]];
echo json_encode(kosaraju(6, $roads)) . PHP_EOL;JavaScript
// Kosaraju: returns the strongly connected components
function kosaraju(n, edges) {
const adj = Array.from({ length: n }, () => []);
const radj = Array.from({ length: n }, () => []); // the same roads, arrows flipped
for (const [a, b] of edges) { adj[a].push(b); radj[b].push(a); }
// Pass 1: remember the order in which nodes finish
const seen = new Array(n).fill(false);
const finish = [];
function dfs1(u) {
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) dfs1(v);
finish.push(u);
}
for (let i = 0; i < n; i++) if (!seen[i]) dfs1(i);
// Pass 2: on the flipped graph, start from the last-finished node
const comp = new Array(n).fill(-1);
const groups = [];
function dfs2(u, id) {
comp[u] = id;
groups[id].push(u);
for (const v of radj[u]) if (comp[v] < 0) dfs2(v, id);
}
let count = 0;
for (let k = n - 1; k >= 0; k--) {
const u = finish[k];
if (comp[u] < 0) { groups.push([]); dfs2(u, count++); }
}
return groups.map(g => g.sort((a, b) => a - b)); // tidy output
}
// junctions 1..6 become 0..5
const roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,3],[4,5]];
console.log(JSON.stringify(kosaraju(6, roads)));Java
import java.util.*;
public class Main {
static List<List<Integer>> adj, radj;
static boolean[] seen;
static int[] comp;
static List<Integer> finish = new ArrayList<>();
static List<List<Integer>> groups = new ArrayList<>();
static void dfs1(int u) {
seen[u] = true;
for (int v : adj.get(u)) if (!seen[v]) dfs1(v);
finish.add(u);
}
static void dfs2(int u, int id) {
comp[u] = id;
groups.get(id).add(u);
for (int v : radj.get(u)) if (comp[v] < 0) dfs2(v, id);
}
// Kosaraju: returns the strongly connected components
static List<List<Integer>> kosaraju(int n, int[][] edges) {
adj = new ArrayList<>();
radj = new ArrayList<>(); // the same roads, arrows flipped
for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); radj.add(new ArrayList<>()); }
for (int[] e : edges) { adj.get(e[0]).add(e[1]); radj.get(e[1]).add(e[0]); }
// Pass 1: remember the order in which nodes finish
seen = new boolean[n];
for (int i = 0; i < n; i++) if (!seen[i]) dfs1(i);
// Pass 2: on the flipped graph, start from the last-finished node
comp = new int[n];
Arrays.fill(comp, -1);
int count = 0;
for (int k = n - 1; k >= 0; k--) {
int u = finish.get(k);
if (comp[u] < 0) { groups.add(new ArrayList<>()); dfs2(u, count++); }
}
for (List<Integer> g : groups) Collections.sort(g); // tidy output
return groups;
}
public static void main(String[] args) {
// junctions 1..6 become 0..5
int[][] roads = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 3}, {4, 5}};
System.out.println(kosaraju(6, roads));
}
}Go
package main
import (
"fmt"
"sort"
)
// kosaraju returns the strongly connected components.
func kosaraju(n int, edges [][2]int) [][]int {
adj := make([][]int, n)
radj := make([][]int, n) // the same roads, arrows flipped
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
radj[e[1]] = append(radj[e[1]], e[0])
}
// Pass 1: remember the order in which nodes finish
seen := make([]bool, n)
var finish []int
var dfs1 func(u int)
dfs1 = func(u int) {
seen[u] = true
for _, v := range adj[u] {
if !seen[v] {
dfs1(v)
}
}
finish = append(finish, u)
}
for i := 0; i < n; i++ {
if !seen[i] {
dfs1(i)
}
}
// Pass 2: on the flipped graph, start from the last-finished node
comp := make([]int, n)
for i := range comp {
comp[i] = -1
}
var groups [][]int
var dfs2 func(u, id int)
dfs2 = func(u, id int) {
comp[u] = id
groups[id] = append(groups[id], u)
for _, v := range radj[u] {
if comp[v] < 0 {
dfs2(v, id)
}
}
}
for k := n - 1; k >= 0; k-- {
u := finish[k]
if comp[u] < 0 {
groups = append(groups, nil)
dfs2(u, len(groups)-1)
}
}
for _, g := range groups {
sort.Ints(g) // tidy output
}
return groups
}
func main() {
// junctions 1..6 become 0..5
roads := [][2]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 3}, {4, 5}}
fmt.Println(kosaraju(6, roads))
}Time: O(V + E) · Extra space: O(V + E). Two full DFS passes plus building the flipped graph: all linear in the size of the graph.
Watch out for
- Forgetting to reverse the edges before the second pass. On the original graph the second DFS would leak into other components.
- Processing the finish list from the first element instead of the last one in pass 2.
- Resetting the visited flags between pass 1 and 2 incorrectly. Pass 2 needs its own fresh marks (here, the
comparray).
Quick check
- What is the second pass of Kosaraju run on?
- The graph with all edges reversed
- A sorted copy of the nodes
- Only the first component
- The original graph
- In which order do we start DFS searches in pass 2?
- Random order
- From the last-finished node backwards
- By node number
- What does each DFS tree in pass 2 represent?
- One strongly connected component
- A cycle only
- A shortest path