Sub topic 7
Kosaraju's Algorithm: Two Passes of DFS
This chapter assumes you already know recursive depth-first search (DFS), how to read DFS finish times, what the transpose graph is, and what the condensation DAG is, all covered in earlier chapters. Here we put those pieces together into a complete algorithm. The proof of why it works comes in the next chapter. This chapter covers how the algorithm runs, how to implement it, and the mistakes that most often break it.
The Idea in One Paragraph
Kosaraju's algorithm finds every strongly connected component (SCC) with two depth-first searches. The first DFS runs on the original graph and records each vertex at the moment it finishes. The second DFS runs on the transpose graph, where every edge is reversed, and it picks start vertices in decreasing order of finish time. Each DFS tree in the second pass is exactly one SCC.
The second pass works because of where it starts. The vertex with the latest finish time lies in a source component of the condensation DAG. In the transpose, that component becomes a sink, so a DFS started there cannot leak into any other component. Once that component is labeled, the next unlabeled vertex in finish order behaves the same way relative to the vertices that are still unlabeled.
The Algorithm Step by Step
- Mark every vertex unvisited. For each unvisited vertex, run DFS on the original graph. When a vertex finishes, meaning all its outgoing edges have been explored, append it to a list
order. - Build the transpose: for every edge
u → v, addv → u. - Walk
orderfrom the end to the start, which is decreasing finish time. Whenever you reach a vertex that has no component label yet, run DFS on the transpose from it. Give every vertex this DFS reaches the current component number, then increment the number.
The second DFS skips vertices that already have a label. That rule keeps each search inside one component.
Implementation
def kosaraju(n, adj):
visited = [False] * n
order = []
def dfs1(u):
visited[u] = True
for v in adj[u]:
if not visited[v]:
dfs1(v)
order.append(u) # record u at its finish time
for u in range(n):
if not visited[u]:
dfs1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
def dfs2(u, c):
comp[u] = c
for v in radj[u]:
if comp[v] == -1:
dfs2(v, c)
c = 0
for u in reversed(order): # decreasing finish time
if comp[u] == -1:
dfs2(u, c)
c += 1
return comp
# Example graph with SCCs {0,1,2}, {3,4,5}, {6,7}
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(kosaraju(8, adj)) # [1, 1, 1, 2, 2, 2, 0, 0]A few details matter here:
orderis a postorder list. A vertex is appended after its whole subtree has finished, so the last element has the largest finish time. You never need explicit timestamps, because their relative order is all the algorithm uses.visitedandcompare separate arrays. The second pass usescomp[v] == -1as its "unvisited" test, so it needs no second boolean array.- The function returns one label per vertex. If you want lists of vertices instead, group the vertices by label afterward.
Tracing the Example
Here is the example graph. The edges 2 → 3 and 6 → 5 are the only ones that cross between components.
Pass 1 on the original graph
DFS starts at 0 and follows the path 0, 1, 2, 3, 4, 5. Vertex 5's only edge leads back to 3, which is already visited, so 5 finishes first. The search then unwinds. Next the outer loop reaches 6, which visits 7.
| Vertex | Discovery | Finish |
|---|---|---|
| 0 | 1 | 12 |
| 1 | 2 | 11 |
| 2 | 3 | 10 |
| 3 | 4 | 9 |
| 4 | 5 | 8 |
| 5 | 6 | 7 |
| 6 | 13 | 16 |
| 7 | 14 | 15 |
So order = [5, 4, 3, 2, 1, 0, 7, 6], and the second pass visits 6, 7, 0, 1, 2, 3, 4, 5.
Pass 2 on the transpose
The transpose has edges 1→0, 2→1, 0→2, 3→2, 4→3, 5→4, 3→5, 5→6, 7→6, 6→7.
| Start vertex | Reached in the transpose | Label |
|---|---|---|
| 6 | 6, 7 (edge 6→7; 7→6 leads back) | 0 |
| 7 | already labeled, skipped | — |
| 0 | 0, 2, 1 | 1 |
| 1, 2 | already labeled, skipped | — |
| 3 | 3, 5, 4 (edges 3→2 and 5→6 hit labeled vertices) | 2 |
| 4, 5 | already labeled, skipped | — |
When the search starts at 3, the transpose edges 3 → 2 and 5 → 6 lead into components that are already labeled, so the search stops at them. Those edges are the reversed cross-component edges. Because their target components were finished earlier, they cannot merge two SCCs.
Common Mistakes
The smallest graph that exposes most bugs has two vertices and a single edge 1 → 0. Its SCCs are {0} and {1}. The outer loop of pass 1 visits 0 first, so order = [0, 1] and the decreasing finish order is 1, 0.
| Mistake | What happens on `1 → 0` |
|---|---|
| Second pass on the original graph instead of the transpose | Starts at 1, follows `1 → 0`, and merges both vertices into one component |
| Visiting in discovery order (0, 1) instead of decreasing finish order | Starts at 0, follows transpose edge `0 → 1`, and merges both vertices |
| Visiting in increasing finish order (0, 1) on the transpose | Same failure as discovery order |
| Correct: decreasing finish order on the transpose | Starts at 1, which has no transpose edges, so it gets `{1}`. Then 0 gets `{0}` |
There is one valid variant. You can run the first pass on the transpose and the second pass on the original graph, again in decreasing finish order of the first pass. The two graphs simply swap roles. The labels then come out in reverse topological order. Mixing the two variants, for example running both passes on the same graph, is a bug.
Other mistakes show up in real code:
- Appending at discovery instead of finish. If
order.append(u)goes before the loop over neighbors, you get preorder, and the algorithm breaks as shown above. - Restarting
visitedbetween DFS trees in pass 1. Thevisitedarray must be shared across all calls in the first pass. Otherwise vertices get appended more than once. - Forgetting isolated vertices. Both outer loops must cover all
nvertices. A vertex with no edges is its own SCC and must still get a label. - Self-loops and parallel edges. Neither one causes trouble. A self-loop
u → uis skipped becauseuis already visited, and duplicate edges only repeat a check. Both still count toward theEin the running time.
Cost at a Glance
Each pass touches every vertex once and every edge once, and building the transpose takes another O(V + E). Memory holds the graph twice, once as adj and once as radj, plus the order, visited, and comp arrays. The complexity chapter analyzes this in detail, and the comparison chapter weighs it against Tarjan's algorithm, which needs no transpose.
Exercises
Exercise
Run Kosaraju's algorithm by hand on the graph with 5 vertices and edges 0→1, 1→2, 2→0, 1→3, 3→4, with adjacency lists in that order. Give the finish order from pass 1, the vertices visited in pass 2, and the final comp array.
Show answer
Pass 1 from 0 visits 0, 1, 2. Vertex 2's edge to 0 is already visited, so 2 finishes. Then 1 visits 3, which visits 4. The finishes are 4, then 3, then 1, then 0, so order = [2, 4, 3, 1, 0]. Pass 2 visits in the order 0, 1, 3, 4, 2. The transpose has edges 1→0, 2→1, 0→2, 3→1, 4→3. Starting at 0 reaches 2 and then 1, which gets label 0. Starting at 3, its transpose edge goes to 1, which is already labeled, so {3} gets label 1. Starting at 4, its edge goes to 3, which is labeled, so {4} gets label 2. The result is comp = [0, 0, 0, 1, 2], a topological order: {0,1,2} → {3} → {4}.
Exercise
A colleague changes the second loop to for u in order: (increasing finish time) but keeps the DFS on the transpose. Give a graph where this returns wrong components, and explain what goes wrong.
Show answer
Use two vertices with the single edge 1→0. Pass 1 gives order = [0, 1]. The modified loop starts at 0 and follows the transpose edge 0→1, so both vertices get the same label, although {0} and {1} are separate SCCs. Increasing finish order can start in a component that is a source in the transpose, and a DFS from there leaks into every component that can reach it in the original graph.
Exercise
Write a function scc_lists(n, adj) that uses kosaraju to return a list of components, each a list of vertices, ordered so that the component list follows a topological order of the condensation.
Show answer
Group the vertices by label. Because Kosaraju's labels are already in topological order, indexing by label keeps that order: def scclists(n, adj): comp = kosaraju(n, adj) k = max(comp, default=-1) + 1 groups = [[] for in range(k)] for v in range(n): groups[comp[v]].append(v) return groups On the chapter's example it returns [[6, 7], [0, 1, 2], [3, 4, 5]].