Kosaraju's Algorithm
Run one depth-first search and write down the order in which vertices finish. Reverse every edge. Then run a second search on the reversed graph, starting from the vertex that finished last. Each tree that second search grows is one strongly connected component, and it cannot spill into the next.
Two Searches and One Reversal
A strongly connected component (SCC) is a largest group of vertices in a directed graph where every vertex can reach every other one. The strongly connected components lesson explains the idea and the graph of components; this lesson is about one way to compute them.
The Kosaraju algorithm (S. Rao Kosaraju, 1978; published independently by Micha Sharir in 1981) needs nothing beyond plain depth-first search. The first search does not find any components. It only produces an order. The second search, run on the graph with every edge reversed, uses that order to pick its start vertices, and each start collects exactly one component.
The Steps
- Run DFS from every unvisited vertex in turn. When a vertex has no unexplored edges left, append it to a list: this is the finish order
- Build the transpose: for every edge u → v, add v → u to a new adjacency list
- Go through the finish list from the end to the start (reverse postorder). Skip vertices already assigned
- From each unassigned vertex, run DFS on the transpose. Every vertex it reaches that is not yet assigned belongs to this component
- When the list is used up, every vertex has a component number
The example graph has 8 vertices and 11 edges: 0 → 1, 1 → 3, 1 → 2, 2 → 0, 2 → 7, 3 → 4, 4 → 3, 4 → 5, 5 → 6, 6 → 5, 7 → 4. Adjacency lists keep that order, so vertex 1 tries 3 before 2.
Worked Example
Pass 1 starts at 0 and goes 0 → 1 → 3 → 4 → 5 → 6. Vertex 6 can only go back to 5, which is already visited, so 6 finishes first. Then 5, 4 and 3 finish. Back at 1, the search tries 2, then 2 → 7; 7 only leads to 4, which is done, so 7 finishes, then 2, 1 and 0. The finish order is 6, 5, 4, 3, 7, 2, 1, 0.
Pass 2 reads that list backwards and searches the transpose. From 0 it reaches 2 and 1: component {0, 1, 2}. The next unassigned vertex in the list is 7; in the transpose its only edge goes to 2, which is taken, so {7} is a component on its own. Then 3 collects {3, 4}, and 5 collects {5, 6}. Four components, found in the order {0, 1, 2}, {7}, {3, 4}, {5, 6}.
- Edges between components: {0, 1, 2} → {7}, {0, 1, 2} → {3, 4}, {7} → {3, 4}, {3, 4} → {5, 6}
- That is also the order pass 2 found them in: a topological order of the components
- The Tarjan's algorithm lesson runs the same graph and gets the same four groups in the opposite order
Terms, operations, and practical uses
Key terms
- Finish orderThe order in which DFS completes vertices, also called postorder.
- TransposeThe same graph with every edge reversed; it has the same components.
- Source componentA component no edge enters; the last finisher of pass 1 lies in one.
- Sink componentA component no edge leaves; a search started inside it stays inside.
Related lessons and problems
- Strongly Connected ComponentsThe definition, the component graph, and Kosaraju vs Tarjan.
- Tarjan's AlgorithmThe same components from one DFS with low-link values.
- Depth-First SearchThe traversal both passes are built on.
- Topological SortReverse finish order on a graph without cycles.
- Strongly Connected Components (problem)Count the components in a directed graph.
Code in Python, C++ and Java
def finish_order(n, adj):
seen = [False] * n
order = []
for start in range(n):
if seen[start]:
continue
seen[start] = True
stack = [(start, 0)]
while stack:
u, i = stack[-1]
if i < len(adj[u]):
stack[-1] = (u, i + 1)
v = adj[u][i]
if not seen[v]:
seen[v] = True
stack.append((v, 0))
else:
stack.pop()
order.append(u)
return order
def transpose(n, adj):
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
return radj
def collect(n, graph, starts):
comp = [-1] * n
groups = []
for s in starts:
if comp[s] != -1:
continue
comp[s] = len(groups)
group, stack = [], [s]
while stack:
u = stack.pop()
group.append(u)
for v in graph[u]:
if comp[v] == -1:
comp[v] = len(groups)
stack.append(v)
groups.append(sorted(group))
return groups, comp
def kosaraju(n, adj):
order = finish_order(n, adj)
return collect(n, transpose(n, adj), reversed(order))
edges = [(0, 1), (1, 3), (1, 2), (2, 0), (2, 7), (3, 4), (4, 3), (4, 5), (5, 6), (6, 5), (7, 4)]
n = 8
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
print("finish order:", finish_order(n, adj))
groups, comp = kosaraju(n, adj)
print("components:", groups)
dag = sorted({(comp[u], comp[v]) for u, v in edges if comp[u] != comp[v]})
print("condensation edges:", dag)
wrong, _ = collect(n, adj, reversed(finish_order(n, adj)))
print("pass 2 on the original graph:", wrong)
wrong, _ = collect(n, transpose(n, adj), finish_order(n, adj))
print("pass 2 in finish order, not reversed:", wrong)
m = 100000
chain = [[i + 1] for i in range(m - 1)] + [[0]]
print("ring of", m, "vertices:", len(kosaraju(m, chain)[0]), "component")#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Graph = vector<vector<int>>;
vector<int> finishOrder(const Graph& adj) {
int n = adj.size();
vector<bool> seen(n, false);
vector<int> order;
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
seen[start] = true;
vector<pair<int, size_t>> stack = {{start, 0}};
while (!stack.empty()) {
auto& [u, i] = stack.back();
if (i < adj[u].size()) {
int v = adj[u][i++];
if (!seen[v]) {
seen[v] = true;
stack.push_back({v, 0});
}
} else {
order.push_back(u);
stack.pop_back();
}
}
}
return order;
}
Graph transpose(const Graph& adj) {
Graph radj(adj.size());
for (int u = 0; u < (int)adj.size(); u++)
for (int v : adj[u]) radj[v].push_back(u);
return radj;
}
vector<vector<int>> collect(const Graph& g, const vector<int>& starts, vector<int>& comp) {
comp.assign(g.size(), -1);
vector<vector<int>> groups;
for (int s : starts) {
if (comp[s] != -1) continue;
int id = groups.size();
comp[s] = id;
vector<int> group, stack = {s};
while (!stack.empty()) {
int u = stack.back();
stack.pop_back();
group.push_back(u);
for (int v : g[u])
if (comp[v] == -1) {
comp[v] = id;
stack.push_back(v);
}
}
sort(group.begin(), group.end());
groups.push_back(group);
}
return groups;
}
vector<vector<int>> kosaraju(const Graph& adj, vector<int>& comp) {
vector<int> order = finishOrder(adj);
reverse(order.begin(), order.end());
return collect(transpose(adj), order, comp);
}
string show(const vector<int>& v) {
string s = "[";
for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
return s + "]";
}
string show(const vector<vector<int>>& g) {
string s = "[";
for (size_t i = 0; i < g.size(); i++) s += (i ? ", " : "") + show(g[i]);
return s + "]";
}
int main() {
vector<pair<int, int>> edges = {{0, 1}, {1, 3}, {1, 2}, {2, 0}, {2, 7}, {3, 4}, {4, 3}, {4, 5}, {5, 6}, {6, 5}, {7, 4}};
int n = 8;
Graph adj(n);
for (auto [u, v] : edges) adj[u].push_back(v);
cout << "finish order: " << show(finishOrder(adj)) << "\n";
vector<int> comp;
cout << "components: " << show(kosaraju(adj, comp)) << "\n";
set<pair<int, int>> dag;
for (auto [u, v] : edges)
if (comp[u] != comp[v]) dag.insert({comp[u], comp[v]});
cout << "condensation edges: [";
bool first = true;
for (auto [a, b] : dag) {
cout << (first ? "" : ", ") << "(" << a << ", " << b << ")";
first = false;
}
cout << "]\n";
vector<int> order = finishOrder(adj), rev(order.rbegin(), order.rend()), tmp;
cout << "pass 2 on the original graph: " << show(collect(adj, rev, tmp)) << "\n";
cout << "pass 2 in finish order, not reversed: " << show(collect(transpose(adj), order, tmp)) << "\n";
int m = 100000;
Graph ring(m);
for (int i = 0; i < m; i++) ring[i].push_back((i + 1) % m);
cout << "ring of " << m << " vertices: " << kosaraju(ring, tmp).size() << " component\n";
}import java.util.*;
public class Main {
static List<Integer> finishOrder(List<List<Integer>> adj) {
int n = adj.size();
boolean[] seen = new boolean[n];
List<Integer> order = new ArrayList<>();
for (int start = 0; start < n; start++) {
if (seen[start]) continue;
seen[start] = true;
Deque<int[]> stack = new ArrayDeque<>();
stack.push(new int[]{start, 0});
while (!stack.isEmpty()) {
int[] top = stack.peek();
int u = top[0];
if (top[1] < adj.get(u).size()) {
int v = adj.get(u).get(top[1]++);
if (!seen[v]) {
seen[v] = true;
stack.push(new int[]{v, 0});
}
} else {
stack.pop();
order.add(u);
}
}
}
return order;
}
static List<List<Integer>> transpose(List<List<Integer>> adj) {
List<List<Integer>> radj = new ArrayList<>();
for (int i = 0; i < adj.size(); i++) radj.add(new ArrayList<>());
for (int u = 0; u < adj.size(); u++)
for (int v : adj.get(u)) radj.get(v).add(u);
return radj;
}
static List<List<Integer>> collect(List<List<Integer>> g, List<Integer> starts, int[] comp) {
Arrays.fill(comp, -1);
List<List<Integer>> groups = new ArrayList<>();
for (int s : starts) {
if (comp[s] != -1) continue;
int id = groups.size();
comp[s] = id;
List<Integer> group = new ArrayList<>();
Deque<Integer> stack = new ArrayDeque<>();
stack.push(s);
while (!stack.isEmpty()) {
int u = stack.pop();
group.add(u);
for (int v : g.get(u))
if (comp[v] == -1) {
comp[v] = id;
stack.push(v);
}
}
Collections.sort(group);
groups.add(group);
}
return groups;
}
static List<List<Integer>> kosaraju(List<List<Integer>> adj, int[] comp) {
List<Integer> order = finishOrder(adj);
Collections.reverse(order);
return collect(transpose(adj), order, comp);
}
public static void main(String[] args) {
int[][] edges = {{0, 1}, {1, 3}, {1, 2}, {2, 0}, {2, 7}, {3, 4}, {4, 3}, {4, 5}, {5, 6}, {6, 5}, {7, 4}};
int n = 8;
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]);
System.out.println("finish order: " + finishOrder(adj));
int[] comp = new int[n];
System.out.println("components: " + kosaraju(adj, comp));
TreeSet<String> dag = new TreeSet<>();
for (int[] e : edges)
if (comp[e[0]] != comp[e[1]]) dag.add("(" + comp[e[0]] + ", " + comp[e[1]] + ")");
System.out.println("condensation edges: [" + String.join(", ", dag) + "]");
List<Integer> order = finishOrder(adj), rev = new ArrayList<>(order);
Collections.reverse(rev);
System.out.println("pass 2 on the original graph: " + collect(adj, rev, comp));
System.out.println("pass 2 in finish order, not reversed: " + collect(transpose(adj), order, comp));
int m = 100000;
List<List<Integer>> ring = new ArrayList<>();
for (int i = 0; i < m; i++) ring.add(new ArrayList<>(List.of((i + 1) % m)));
System.out.println("ring of " + m + " vertices: " + kosaraju(ring, new int[m]).size() + " component");
}
}Step through it
Running on 0→1, 1→3, 1→2, 2→0, 2→7, 3→4, 4→3, 4→5, 5→6, 6→5, 7→4
Why the Reverse Finish Order Works
Collapse each component to a single node and you get a directed graph with no cycles. The whole proof rests on one fact about it: if some edge goes from component C to component D, the latest finish time in C is later than every finish time in D. If pass 1 enters C first, it reaches all of D before leaving C, so C's first vertex finishes after all of D. If it enters D first, it cannot get back to C at all (that would make C and D one component), so all of D finishes before C is even entered.
So the vertex at the end of the finish list sits in a component that nothing else points into, a source. Reversing every edge keeps each component intact, because a cycle reversed is still a cycle, but turns that source into a sink: in the transpose no edge leaves it. A search started there collects its component and then stops. With that component marked, the next unassigned vertex in reverse finish order lies in a source of what remains, and the argument repeats.
- Only finish times matter in pass 1; discovery order would not give the guarantee
- Pass 2 needs no special care: any DFS or BFS that skips assigned vertices works
Building the Transpose of a Graph
The transpose of a graph has the same vertices and every edge flipped. With adjacency lists, walk every list once and append u to the list of v: O(V + E) time and a second O(V + E) structure. With an adjacency matrix it is the matrix transpose, O(V²).
Many implementations build both lists while reading the input, so the reversal costs nothing extra later. What you cannot do is skip the reversal and run pass 2 on the original graph, which the next section shows.
Two Mistakes That Merge Everything
Pass 2 on the original graph. Starting from 0 again, the search follows the original edges 0 → 1 → 3 → 4 → 5 → 6 and 2 → 7. It reaches all 8 vertices and reports one giant component. In the original direction the last finisher is a source, and a search from a source can reach everything downstream.
Finish order not reversed. Taking pass-2 start vertices from the front of the finish list starts at 6. In the transpose 6 reaches 5, then 4, then 3 and 7, then 1, 2 and 0: again one component of size 8. The first finisher lies in a sink of the original graph, which becomes a source once the edges are reversed.
- Both mistakes merge components; neither ever splits one
- A quick check: every component must be a set the other algorithm also finds
Kosaraju Algorithm Time Complexity
Pass 1 visits every vertex and edge once, building the transpose does the same, and so does pass 2. Kosaraju's algorithm therefore runs in O(V + E) time on adjacency lists and O(V²) on a matrix. Memory is O(V) for the visited flags, finish list and component numbers, plus O(V + E) for the transpose.
The real risk is recursion depth, not speed. A cycle of 100,000 vertices makes a recursive pass 1 go 100,000 calls deep. The code on this page keeps an explicit stack of (vertex, next edge index) pairs and appends a vertex to the finish list when its pair is popped, which gives exactly the recursive finish order without the call stack. Pass 2 does not care about order, so a plain stack is enough there.
- Three linear passes: DFS, transpose, DFS
- Explicit stack in pass 1: push (vertex, 0), advance the index, finish on pop
- The 100,000-vertex ring comes out as one component without any recursion
What You Do With the Components
Because pass 2 produces components in topological order, you get the component graph almost for free: number the components as they are found, then every original edge u → v with different numbers is an edge between components, and it always goes from a smaller number to a larger one. Problems that are hard on a graph with cycles, such as longest path or counting reachable vertices, become dynamic programming over that order.
The same machinery decides 2-SAT, where a formula is unsatisfiable exactly when a variable and its negation land in one component. For how Kosaraju compares with Tarjan's single-pass method on memory and speed, see the comparison in the strongly connected components lesson.
- Strongly Connected Components (Kosaraju): count the components
- Course Schedule: any component with more than one course is a prerequisite loop