Sub topic 12
Strongly Connected Components with Kosaraju's Algorithm
This chapter assumes you can already do three things. You can build an adjacency list from an edge list. You can write an iterative depth-first search (DFS) with an explicit stack. You know what a strongly connected component (SCC) is: a maximal set of vertices in a directed graph where every vertex can reach every other vertex by following edges in their direction. All of that was covered in earlier chapters. Here we turn the definition into an algorithm that finds every SCC in O(V + E) time.
Kosaraju's algorithm runs two depth-first passes. The first pass runs on the original graph and records the order in which vertices finish. The second pass runs on the reversed graph and visits vertices in reverse finish order. Each traversal in the second pass collects exactly one SCC. The steps are short. The real work is understanding why they are correct, because small changes to them quietly produce wrong answers.
Why a Single Traversal Is Not Enough
In an undirected graph, one BFS or DFS from a start vertex finds its whole component, because reachability is symmetric. In a directed graph, a DFS from vertex u finds everything u can reach. That set can include vertices that cannot reach u back. If you label the whole reachable set as one component, you merge SCCs that only connect in one direction.
Take the example graph used in this chapter. Its edges are 0→1, 1→2, 2→0, 2→3, 3→4, and 4→3. Vertices 0, 1, and 2 form a cycle, and so do 3 and 4. A single edge, 2→3, runs from the first cycle into the second. A DFS from 0 reaches all five vertices, but {0, 1, 2} and {3, 4} are separate SCCs, because nothing leads from 3 or 4 back to the first cycle.
A DFS from 3 is different. It reaches only 3 and 4, which is exactly one SCC. So the order you start from matters. A traversal stays inside one SCC when it starts in an SCC that has no edges leaving it to unvisited SCCs. Kosaraju's algorithm is a way to find those starting points in the right order without knowing the SCCs in advance.
The Condensation Graph
Picture each SCC collapsed into a single node, with an edge from SCC C to SCC C' whenever some edge runs from a vertex in C to a vertex in C'. The result is called the condensation. It is always a directed acyclic graph (DAG). If it had a cycle, every SCC on that cycle could reach every other one, so they would all be a single SCC, which is a contradiction.
Every DAG has at least one sink, which is a node with no outgoing edges. A DFS started inside a sink SCC cannot leave it. If we could repeatedly find a sink SCC, traverse it, remove it, and continue, we would extract every SCC correctly. Kosaraju's algorithm does this using two facts.
- Finish times order the condensation. Run a full DFS (restarting from every unvisited vertex) and record when each vertex finishes, meaning when all of its descendants are done. If the condensation has an edge from C to C', the latest finish time in C is greater than the latest finish time in C'. As a result, the vertex that finishes last overall lies in a source SCC of the condensation.
- Reversing edges swaps sources and sinks. The reversed graph has exactly the same SCCs, since a cycle reversed is still a cycle. Its condensation is the original condensation with every edge flipped, so a source SCC of the original becomes a sink of the reversed graph.
Put the two facts together. The last vertex to finish sits in an SCC that is a sink in the reversed graph. A traversal of the reversed graph from that vertex collects exactly its SCC. After marking those vertices, the next unmarked vertex in reverse finish order lies in an SCC that is a sink among the SCCs still unmarked, and the argument repeats.
Why the finish-time fact holds
Suppose an edge u→v runs from SCC C to SCC C'. There are two cases. If the DFS first enters C' before touching C, it finishes all of C' before it ever reaches C, because C' cannot reach C. Every vertex in C then finishes later. If the DFS first enters C at some vertex x, then everything in C and C' is reachable from x and still unvisited. All of it becomes a descendant of x, so x finishes after all of it. Either way, C holds the larger maximum finish time.
The Implementation
The first pass must record post-order, meaning a vertex is appended only when all of its neighbors are done. A plain stack-based DFS that pops a vertex and immediately records it gives the wrong order. The code below stores (vertex, next_neighbor_index) frames on the stack, which simulates recursion exactly. A vertex stays on the stack until its neighbor index runs past the end of its list, and only then is it appended to order.
def kosaraju_scc(n, edges):
adj = [[] for _ in range(n)]
radj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
radj[v].append(u)
visited = [False] * n
order = []
for s in range(n):
if visited[s]:
continue
visited[s] = True
stack = [(s, 0)]
while stack:
u, i = stack[-1]
if i < len(adj[u]):
stack[-1] = (u, i + 1)
v = adj[u][i]
if not visited[v]:
visited[v] = True
stack.append((v, 0))
else:
stack.pop()
order.append(u)
comp = [-1] * n
count = 0
for s in reversed(order):
if comp[s] != -1:
continue
comp[s] = count
stack = [s]
while stack:
u = stack.pop()
for v in radj[u]:
if comp[v] == -1:
comp[v] = count
stack.append(v)
count += 1
return count, comp
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3)]
print(kosaraju_scc(5, edges))
# (2, [0, 0, 0, 1, 1])The second pass does not care about visit order inside a component. It only needs to collect the vertices that can reach s in the original graph and are still unlabeled. So it uses the simpler pop-and-push DFS. A BFS would work just as well.
Tracing the Example
Pass 1 starts at 0. The DFS goes 0 → 1 → 2. Vertex 0, a neighbor of 2, is already visited, so the DFS continues to 3 and then 4. Vertex 4's only neighbor, 3, is visited, so 4 finishes first. Then 3, 2, 1, and 0 finish in that order. The finish order is [4, 3, 2, 1, 0].
Pass 2 walks the finish order in reverse: 0, 1, 2, 3, 4.
| Step | Start vertex | Reversed edges followed | Newly labeled | Label |
|---|---|---|---|---|
| 1 | 0 | 0←2, 2←1 | 0, 2, 1 | 0 |
| 2 | 1 | already labeled | none | none |
| 3 | 2 | already labeled | none | none |
| 4 | 3 | 3←4 (3←2 is skipped because 2 is labeled) | 3, 4 | 1 |
| 5 | 4 | already labeled | none | none |
At step 4, the reversed edge from 3 back to 2 does exist. The traversal skips it because 2 already has a label. This check is what keeps the second pass from leaking into an SCC that was already extracted.
A Free Bonus: Topological Order of SCCs
Labels are assigned in topological order of the condensation. Label 0 is a source SCC, and every condensation edge goes from a lower label to a higher one. This follows from the fact that the second pass visits SCCs in decreasing order of maximum finish time. Many applications need exactly this order. Examples include solving 2-SAT, ordering build steps that contain cyclic dependency groups, and dynamic programming over a DAG of SCCs. The function below builds the condensation. Append it to the previous code block and run it.
def condensation(n, edges):
count, comp = kosaraju_scc(n, edges)
dag = [set() for _ in range(count)]
for u, v in edges:
if comp[u] != comp[v]:
dag[comp[u]].add(comp[v])
return comp, [sorted(s) for s in dag]
print(condensation(5, edges))
# ([0, 0, 0, 1, 1], [[1], []])Complexity
| Resource | Cost | Where it comes from |
|---|---|---|
| Time | O(V + E) | Building `adj` and `radj`, then two traversals, each touching every vertex and edge once |
| Extra space | O(V + E) | Two adjacency lists, plus O(V) for `visited`, `order`, `comp`, and the stacks |
The algorithm has the same asymptotic cost as undirected labeling, but the constant factor is roughly double. It stores the graph twice and traverses it twice. When memory is tight, that second adjacency list is the main cost. Tarjan's algorithm, covered in the next chapter, avoids both the reversed graph and the second pass.
Common Mistakes
- Forgetting to reverse the graph. If the second pass traverses
adjinstead ofradj, the start vertex sits in a source SCC, and a traversal from a source can reach everything downstream. With edges 0→1 only, the finish order is[1, 0]. Pass 2 starts at 0, follows 0→1, and wrongly reports one SCC. - Forgetting to reverse the order. Walking
orderforward starts from vertices in sink SCCs of the original graph, which are sources inradj. The second traversal then leaks across SCC boundaries. - Using recursion on large graphs. A recursive first pass is the textbook version, but a long path of 10,000 vertices exceeds CPython's default recursion limit of 1000. Raising the limit with
sys.setrecursionlimitcan crash the interpreter with a C stack overflow. The frame-stack version above has no such limit. - Restarting only from vertex 0. Pass 1 must loop over every vertex. Otherwise vertices unreachable from the first start never get a finish time and never get labeled.
Self-loops and parallel edges need no special handling. A self-loop u→u only revisits a vertex that is already marked. A vertex with no edges becomes its own SCC of size one.
Exercise
Run kosaraju_scc by hand on n = 4 with edges [(0, 1), (1, 0), (1, 2), (2, 3)]. Give the finish order from pass 1, the returned labels, and explain why vertices 2 and 3 get different labels.
Show answer
Pass 1 from 0 visits 0, 1, 2, 3. Vertex 3 finishes first, then 2, 1, 0, so the order is [3, 2, 1, 0]. Pass 2 starts at 0 and follows reversed edges 0←1 and 1←0, labeling {0, 1} as 0. Next, 2 is unlabeled, so label 1 goes to 2. Its reversed edge leads to 1, which is already labeled. Then 3 gets label 2. The result is (3, [0, 0, 1, 2]). Vertices 2 and 3 are separate SCCs because 3 cannot reach 2. The labels also follow the topological order 0, then 1, then 2.
Exercise
A colleague changes pass 1 to the simple DFS from the undirected labeling chapter, appending each vertex to order when it is popped. Give a small graph where the final answer becomes wrong.
Show answer
Use edges [(0, 1), (0, 2), (2, 0)], where the SCCs are {0, 2} and {1}. The pop-based DFS from 0 pops 0, pushes 1 and 2, then pops 2 and then 1, so order = [0, 2, 1]. Reversed, pass 2 starts at 1. In radj, 1 has the incoming edge from 0, so the traversal labels 0, and then 2 through the reversed edge 2→0. All three vertices get one label, which is wrong. With true post-order the order is [1, 2, 0], pass 2 starts at 0, and the answer is correct.
Exercise
Why does a vertex with the largest finish time always lie in a source SCC of the condensation, and why does this make it a safe start for pass 2 on the reversed graph?
Show answer
If another SCC had an edge into this vertex's SCC C, that SCC would have a larger maximum finish time than C. That contradicts our vertex finishing last overall, so no edge enters C, and C is a source. In the reversed graph every edge flips, so C has no outgoing edges to other SCCs. A traversal from the vertex can therefore reach only C, and it reaches all of C because SCCs are the same in both graphs.