Sub topic 13
Tarjan's Single-Pass Algorithm
Kosaraju's algorithm, from the previous chapter, needs two full traversals and a reversed copy of the graph. Robert Tarjan's 1972 algorithm finds the same strongly connected components (SCCs) with one depth-first search over the original graph. It stores two integers per vertex and keeps one extra stack. This chapter explains the bookkeeping behind it, gives an iterative implementation, and lists the mistakes people usually make when writing it.
This chapter assumes you already know the following:
- An SCC is a maximal set of vertices in which every vertex can reach every other vertex.
- How iterative DFS with an explicit stack of
(vertex, next_neighbor_index)frames works, as in the Kosaraju chapter. - Basic Big-O reasoning about traversals running in O(V + E).
The Core Idea: Detect the Root of Each SCC
In any DFS of a directed graph, each SCC has exactly one vertex that the search reaches first. Call it the SCC's root. All other vertices of that SCC are discovered after the root and before the root finishes, so they all sit inside the root's DFS subtree.
Tarjan's algorithm works by recognizing each root at the moment it finishes. When a root finishes, the vertices of its SCC are the ones discovered under it that have not already been assigned to some other SCC. The algorithm keeps those vertices together on a stack, so assigning the SCC means popping the stack down to the root.
To recognize a root, the algorithm gives each vertex two numbers:
| Field | Meaning |
|---|---|
| `index[u]` | The order in which DFS discovered `u` (0, 1, 2, ...). It never changes. |
| `low[u]` | The smallest `index` that `u` can reach through its DFS subtree plus at most one edge to a vertex that is still on the SCC stack. |
A vertex u is the root of an SCC exactly when low[u] == index[u]. In that case nothing in u's subtree has a path back to a vertex discovered earlier that is still waiting for an SCC. The vertices above u on the stack therefore cannot belong to any SCC except u's.
The Stack Invariant
Besides the DFS call stack, Tarjan keeps a second stack, the SCC stack. A vertex is pushed onto the SCC stack when it is discovered. It is popped only when its SCC is complete. A finished vertex can therefore stay on the SCC stack. This happens when the vertex can still reach something below it on the stack, which means its SCC root has not finished yet.
Each vertex is in one of three states, and each edge u -> v is handled according to the state of v:
The third branch matters. If v is no longer on the SCC stack, its SCC is already complete, so there is no path from v back to u. Without the on_stack check, low values would leak between components and separate SCCs would be merged.
An Iterative Implementation
Recursive Tarjan is short, but on a long chain of vertices it hits Python's default recursion limit of about 1000 frames. The version below uses the same explicit frame stack as the iterative DFS in earlier chapters. The update of the parent's low happens when a child's frame is popped, which is where a recursive version would update after the recursive call returns.
def tarjan_scc(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
index = [-1] * n # discovery order, -1 means undiscovered
low = [0] * n
on_stack = [False] * n
scc_stack = []
comp = [-1] * n
counter = 0
count = 0
for s in range(n):
if index[s] != -1:
continue
index[s] = low[s] = counter
counter += 1
scc_stack.append(s)
on_stack[s] = True
work = [(s, 0)] # frames: (vertex, next neighbor position)
while work:
u, i = work[-1]
if i < len(adj[u]):
work[-1] = (u, i + 1)
v = adj[u][i]
if index[v] == -1:
index[v] = low[v] = counter
counter += 1
scc_stack.append(v)
on_stack[v] = True
work.append((v, 0))
elif on_stack[v]:
low[u] = min(low[u], index[v])
else:
work.pop()
if work:
parent = work[-1][0]
low[parent] = min(low[parent], low[u])
if low[u] == index[u]:
while True:
w = scc_stack.pop()
on_stack[w] = False
comp[w] = count
if w == u:
break
count += 1
return count, comp
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3)]
print(tarjan_scc(5, edges))
# (2, [1, 1, 1, 0, 0])The partition matches Kosaraju's result on the same graph: {0, 1, 2} and {3, 4}. The labels are swapped, and the next section explains why.
Tracing the Example
The table shows the state at each point where a vertex finishes. The DFS starts at vertex 0 and follows 0 -> 1 -> 2. At vertex 2 it sees the edge 2 -> 0 and continues down 2 -> 3 -> 4.
| Event | `index` | `low` after event | SCC stack (bottom to top) | Action |
|---|---|---|---|---|
| Edge 2 -> 0, 0 on stack | 2: 2 | low[2] = 0 | 0, 1, 2 | none |
| Edge 4 -> 3, 3 on stack | 4: 4 | low[4] = 3 | 0, 1, 2, 3, 4 | none |
| 4 finishes | 4 | 3 | 0, 1, 2, 3, 4 | 3 ≠ 4, stays |
| 3 finishes | 3 | 3 | 0, 1, 2, 3, 4 | root: pop 4, 3 as SCC 0 |
| 2 finishes | 2 | 0 | 0, 1, 2 | stays |
| 1 finishes | 1 | 0 | 0, 1, 2 | stays |
| 0 finishes | 0 | 0 | 0, 1, 2 | root: pop 2, 1, 0 as SCC 1 |
Vertex 4 finishes but stays on the stack, because its root, vertex 3, is still active. When vertex 3 finishes, low[3] is 3, which equals index[3]. Vertex 3 is a root, and everything above it on the stack forms its SCC.
Output Order: Reverse Topological
The condensation of a graph has one node per SCC, with an edge between SCCs whenever an original edge connects them. The condensation is always a directed acyclic graph (DAG). Tarjan completes an SCC only after every SCC reachable from it has been completed. As a result, it emits SCCs in reverse topological order of the condensation: sinks come first. In the example, {3, 4} gets label 0 because it is downstream of {0, 1, 2}.
Kosaraju, as written in the previous chapter, emits SCCs in topological order. If you need a topological order of SCCs, for example to solve 2-SAT or to process dependency groups, Tarjan already provides one. Read its labels from highest to lowest, or treat label 0 as the last group to process.
Tarjan vs Kosaraju
| Criterion | Kosaraju | Tarjan |
|---|---|---|
| DFS passes | 2 | 1 |
| Reversed graph needed | Yes, an extra O(V + E) of memory | No |
| Per-vertex state | visited flag, finish order, label | index, low, on_stack, label |
| Time | O(V + E) | O(V + E) |
| Order of SCCs produced | Topological | Reverse topological |
| Ease of getting it right | Easier; each pass is plain DFS | More subtle; the `low` rules must be exact |
Both run in linear time. Each vertex is pushed and popped once on each stack, and each edge is examined once. Tarjan's practical advantage is that it does not build radj. On large graphs that saves memory and a second pass over the edges. Kosaraju's advantage is that it is easier to check by reading the code.
Common Errors
The following mistakes come up often:
- Initializing
indexto 0. Vertex 0 really does get index 0, so 0 cannot also mean "undiscovered". Use -1 orNone. - Updating the parent's
lowfromindex[u]instead oflow[u]. A tree edge must pass the child's whole reach up to the parent. Usingindex[u]throws that reach away. - Checking the root condition before the vertex has examined all its edges. In the iterative version, the check belongs only in the branch where the frame is exhausted.
- Forgetting to clear
on_stackwhile popping an SCC. If it is never cleared, later cross edges into that SCC are treated as back edges. - Self-loops and isolated vertices. Both form single-vertex SCCs. The code handles them without special cases: a self-loop
u -> usetslow[u]toindex[u], which changes nothing.
Checking Against a Brute-Force Definition
When you modify Tarjan, test it against the definition: two vertices share an SCC exactly when each can reach the other. The check below is O(V·(V + E)), which is fine for small random graphs. It assumes tarjan_scc from above is defined in the same file.
import random
def reach(n, adj, s):
seen = {s}
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return seen
def check(trials=200):
for _ in range(trials):
n = random.randint(1, 8)
edges = [(random.randrange(n), random.randrange(n))
for _ in range(random.randint(0, 15))]
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
r = [reach(n, adj, s) for s in range(n)]
_, comp = tarjan_scc(n, edges)
for a in range(n):
for b in range(n):
same = b in r[a] and a in r[b]
assert same == (comp[a] == comp[b]), (n, edges)
print("all checks passed")
check()Exercise
Run tarjan_scc(4, [(0, 1), (1, 2), (2, 3)]) by hand. What count and comp does it return, and why?
Show answer
It returns (4, [3, 2, 1, 0]). The graph is a simple path, so no vertex can reach an earlier one. Each low[u] stays equal to index[u], and every vertex is the root of its own SCC. Vertex 3 finishes first and gets label 0. Vertex 0 finishes last and gets label 3, which shows the reverse topological output order.
Exercise
Suppose the line "elif on_stack[v]:" is changed to "else:". Give a small graph on which the modified algorithm returns the wrong SCCs.
Show answer
Use the edges [(0, 1), (0, 2), (2, 1)]. DFS visits 0, then 1. Vertex 1 has no outgoing edges, so it becomes its own SCC and leaves the stack. Next, DFS discovers 2 and examines 2 -> 1. With the change, low[2] becomes index[1] = 1, which is less than index[2] = 2. Vertex 2 is then not recognized as a root and stays on the stack until 0 finishes, so {0, 2} is reported as one SCC. The correct answer is three singleton SCCs, because 2 cannot reach 0.
Exercise
You need SCCs of a graph with 50 million edges, and memory is tight. Which algorithm would you choose and why?
Show answer
Tarjan. Both run in O(V + E) time, but Kosaraju builds a reversed adjacency list. That doubles the edge storage and adds a second pass over all edges. Tarjan needs only a few integer arrays of length V and its stacks. Use the iterative version so that deep DFS paths do not overflow the call stack.