Sub topic 10
Tarjan's Algorithm: One Pass with a Stack
Kosaraju's algorithm finds strongly connected components with two depth-first searches, one on the graph and one on its transpose. Tarjan's algorithm needs only one DFS on the original graph. It keeps a stack of vertices whose component has not been decided yet. When the DFS finishes a vertex that turns out to be the root of a component, it pops that whole component off the stack at once.
This chapter assumes you already know recursive DFS on an adjacency list, the four DFS edge types (tree, back, forward, cross), and the definition of low-link values from the previous chapter. The full correctness proof comes in the next chapter. This one covers how the algorithm runs, how to implement it, and where implementations usually go wrong.
The State Each Vertex Carries
Tarjan's algorithm keeps four pieces of bookkeeping:
| Structure | Type | Meaning |
|---|---|---|
| `index[v]` | int or `None` | Discovery order of `v`. `None` means not yet visited. |
| `low[v]` | int | Smallest index reachable from `v`'s DFS subtree using tree edges plus at most one edge to a vertex still on the stack. |
| `stack` | list | Visited vertices whose SCC has not been assigned yet, in discovery order. |
| `on_stack[v]` | bool | Constant-time check for whether `v` is in `stack`. |
Every vertex goes through three states. It starts unvisited. When it is discovered, it is pushed onto the stack. When its component is popped, it leaves the stack and its component is final. A vertex never returns to the stack.
The Algorithm
When strongconnect(v) is called:
- Set
index[v] = low[v] = counter, incrementcounter, and pushv. - For each edge
v → w: - If
wis unvisited, recurse intow, then setlow[v] = min(low[v], low[w]). - Else if
wis on the stack, setlow[v] = min(low[v], index[w]). - Otherwise
walready belongs to a finished component, so ignore the edge. - After all edges are processed, if
low[v] == index[v], thenvis the root of an SCC. Pop vertices untilvcomes off. The popped vertices form exactly one component.
The outer loop calls strongconnect on every vertex that has not been visited, the same way a full DFS covers a graph with several DFS trees.
def tarjan(n, adj):
index = [None] * n
low = [0] * n
on_stack = [False] * n
stack = []
sccs = []
counter = 0
def strongconnect(v):
nonlocal counter
index[v] = low[v] = counter
counter += 1
stack.append(v)
on_stack[v] = True
for w in adj[v]:
if index[w] is None:
strongconnect(w)
low[v] = min(low[v], low[w])
elif on_stack[w]:
low[v] = min(low[v], index[w])
if low[v] == index[v]: # v is the root of an SCC
comp = []
while True:
w = stack.pop()
on_stack[w] = False
comp.append(w)
if w == v:
break
sccs.append(comp)
for v in range(n):
if index[v] is None:
strongconnect(v)
return sccs
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(tarjan(8, adj)) # [[5, 4, 3], [2, 1, 0], [7, 6]]A Full Trace
The example graph has three components: {0, 1, 2}, {3, 4, 5}, and {6, 7}. Edge 2 → 3 leads from the first to the second, and edge 6 → 5 leads from the third to the second.
This table records each step. The low values are the ones in effect after the step.
| Step | Event | low changes | Stack after |
|---|---|---|---|
| 1 | discover 0 (index 0) | low0=0 | 0 |
| 2 | discover 1 (index 1) | low1=1 | 0 1 |
| 3 | discover 2 (index 2) | low2=2 | 0 1 2 |
| 4 | edge 2→0, 0 on stack | low2=0 | 0 1 2 |
| 5 | discover 3, 4, 5 (indices 3, 4, 5) | low=3,4,5 | 0 1 2 3 4 5 |
| 6 | edge 5→3, 3 on stack | low5=3 | 0 1 2 3 4 5 |
| 7 | finish 5 (3≠5), finish 4: low4=min(4,3) | low4=3 | 0 1 2 3 4 5 |
| 8 | finish 3: low3=3 equals index3, pop | none | 0 1 2 |
| 9 | back in 2: low2=min(0, low3=3) | low2=0 | 0 1 2 |
| 10 | finish 2, 1 (low=0); finish 0: root, pop | low1=0 | empty |
| 11 | discover 6 (index 6) | low6=6 | 6 |
| 12 | edge 6→5, 5 is visited but off stack: ignore | none | 6 |
| 13 | discover 7, edge 7→6 on stack | low7=6 | 6 7 |
| 14 | finish 7; finish 6: root, pop | none | empty |
Step 8 shows why the stack is useful. When vertex 3 finishes, everything above it on the stack (4 and 5) was discovered inside 3's subtree and could not reach anything older than 3, so they all belong with 3. Vertices 0, 1, and 2 stay below 3 on the stack because their component is still open.
Step 12 shows why on_stack matters. Vertex 5 is visited, but its component was settled in step 8. The edge 6 → 5 is a cross edge into a finished component. Following it would mean that 6 can reach 5. It would not mean that 5 can reach 6, so the edge must not affect low[6].
Output Order
Components come out in reverse topological order of the condensation DAG. A component is popped only after every component reachable from it has been popped. In the trace, {3, 4, 5} is popped before {0, 1, 2} because A points to B. {6, 7} is popped last only because the outer loop reaches vertex 6 last. It is still emitted after B, which is the component it points to.
Common Implementation Errors
Using a falsy check for "unvisited"
if not index[w]: treats vertex 0 as unvisited because its index is 0. The DFS then visits vertex 0 a second time and pushes it twice. Use None or -1 as the sentinel and compare against it explicitly.
Updating low from finished vertices
If you drop the on_stack[w] test and update low[v] from any visited w, cross edges into finished components lower low values that should not change. Roots are then not recognized, and vertices stay stranded on the stack at the end.
Forgetting to clear `on_stack` on pop
If on_stack[w] stays True after w is popped, later cross edges into w's component count as if w were still open. Different components then merge.
Mixing up `low[w]` and `index[w]`
After a tree edge, take low[w], because the child's subtree may reach higher up the stack. For an edge to a vertex already on the stack, the standard form takes index[w]. Using low[w] in the second case also gives correct SCCs, because any value that stays within the open stack is fine. It is no longer the textbook low-link, though, and it gives wrong answers if you reuse the code for bridges or articulation points. Keep index[w] to avoid that trap.
What You Get for One Pass
Each vertex is pushed once and popped once, and each edge is examined once, so the algorithm runs in linear time. Compared with Kosaraju, Tarjan's algorithm never builds the transpose and needs no finish-order list. It does need two extra arrays, low and on_stack, plus the component stack. Later chapters compare the two algorithms in detail.
Exercise
Run Tarjan's algorithm by hand on adj = [[1], [2], [0], [2]] with the outer loop going 0, 1, 2, 3. What list does it return, and what happens to the edge 3 → 2?
Show answer
It returns [[2, 1, 0], [3]]. The DFS from 0 discovers 0, 1, 2. The edge 2 → 0 sets low2 = 0, so low1 = 0 and low0 = 0, and 0 pops {2, 1, 0}. The outer loop then starts at 3. Vertex 2 is visited but no longer on the stack, so the edge 3 → 2 is ignored. low3 stays 3, and 3 pops itself as a singleton component.
Exercise
Suppose the line elif on_stack[w]: is changed to else:, so every visited w updates low[v] with index[w]. What happens on the chapter's example graph?
Show answer
At the edge 6 → 5, low6 becomes min(6, 5) = 5. Vertex 7 still gets low7 = 6, and after returning, low6 = 5. Because low6 ≠ index6, vertex 6 is never treated as a root. Vertices 6 and 7 stay on the stack when the loop ends, so the result is [[5, 4, 3], [2, 1, 0]] and the component {6, 7} is missing.
Exercise
Why must vertex 0 in the trace stay on the stack when vertex 3 finishes and pops its component, even though 3 was discovered after 0?
Show answer
Vertex 0's component is still open because the DFS has not finished 0. Popping stops at the root 3, and everything below 3 on the stack was discovered before 3, outside its subtree. Those vertices belong to components whose roots are still active on the DFS path.