Sub topic 11
Why Tarjan's Algorithm Works
This chapter assumes you have already read the recursive tarjan function from the previous chapter. You should also know DFS discovery order, the four edge types (tree, back, forward, cross), and what a strongly connected component (SCC) is. The goal is to explain why the test low[v] == index[v] finds exactly the right vertices, and why the vertices popped at that moment form exactly one SCC.
The argument depends on three facts, each built on the one before it:
- Every SCC has a root, the first of its vertices that DFS discovers. Every other vertex of the SCC is a descendant of the root in the DFS tree.
- A vertex stays on the stack until its root finishes. When it is popped, its whole SCC is popped with it.
low[v] == index[v]holds if and only ifvis the root of its SCC.
Fact 1: Each SCC hangs below its root
Take an SCC C, and let r be the first vertex of C that DFS discovers. At that moment, every other vertex of C is still unvisited. Each one is reachable from r along a path that stays inside C, so all of those paths consist of unvisited vertices. The white-path theorem says that any vertex reachable from r through unvisited vertices becomes a descendant of r. So the whole of C is discovered and finished inside the call strongconnect(r).
The DFS tree can contain more than C below r, because other SCCs reachable from r also end up in that subtree. Tarjan's stack is what separates them.
Fact 2: What the stack holds
Each vertex goes through four states. The stack holds every vertex that has been discovered but not yet assigned to a component.
Stack invariant. At any moment, every vertex on the stack can reach some vertex that is currently active, meaning its call is still on the recursion stack. A vertex that is finished and still on the stack is waiting for an active ancestor, its root, to collect it.
The invariant has a useful consequence. Suppose w is on the stack and was discovered before v, which is active. Then w can reach v. If w is active, it is an ancestor of v, and tree edges lead from it down to v. If w is finished, it can reach some active vertex a, and a is also an ancestor of v, because active vertices always form a single root-to-current path. So w reaches a, and a reaches v.
Fact 3: The root test is exact
low[v] is the smallest index that v can reach using tree edges inside its subtree plus at most one final edge to a vertex that is still on the stack.
If low[v] < index[v], then v is not a root. Some vertex w with index[w] = low[v] < index[v] is on the stack and reachable from v. By the consequence above, w also reaches v. So v and w are in the same SCC, and w was discovered first, which means v is not the root.
If v is not a root, then low[v] < index[v]. Let r be the root of v's SCC, so index[r] < index[v]. There is a path from v back to r. Follow it from v. It starts inside v's subtree, and at some point it must take an edge x → y that leaves the subtree, because r lies outside it. Here y was discovered before v, it is in the same SCC as r (it lies on a cycle through r), and it has not been popped, because r is still active. So y is on the stack, and the edge x → y lowers low[x] to at most index[y] < index[v]. That value travels up through low[parent] = min(low[parent], low[child]) until it reaches v.
Why the popped vertices are exactly one SCC
When v passes the root test, the vertices above it on the stack are those discovered in v's subtree and not yet popped.
- Nothing outside the SCC is included. Any other SCC inside
v's subtree has its own root belowv. That root finished earlier, passed its own test, and popped its SCC. - Nothing in the SCC is missing. By Fact 1, every member of the SCC is in
v's subtree, and no deeper root could have popped them, because they belong tov's component.
The ignored edge
The code silently skips an edge v → w when w is visited but no longer on the stack. That is safe: w was popped as part of a finished SCC whose root has completed. If w could reach v, the two would share an SCC. Then v would have been popped together with w, yet v is still active. So w cannot reach v, and the edge crosses between two SCCs. Using it would only drag low[v] toward an unrelated component.
Why the output is in reverse topological order
Suppose an edge leads from SCC A to a different SCC B. If B's root is discovered first, B is finished and popped before anything in A is visited, because B cannot reach A. If A's root is discovered first, all of B is unvisited and reachable from it, so B is discovered inside A's root's subtree and its root finishes first. In both cases B is appended to sccs before A. Every edge of the condensation therefore points from a later component to an earlier one in the output list.
Trace on the example graph
The graph is adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]].
| Step | Event | low change | Pop? |
|---|---|---|---|
| 1 | discover 0, 1, 2 (index 0, 1, 2) | none | |
| 2 | edge 2→0, 0 on stack | low[2] = 0 | |
| 3 | discover 3, 4, 5 (index 3, 4, 5) | none | |
| 4 | edge 5→3, 3 on stack | low[5] = 3 | |
| 5 | 5 and 4 return | low[4] = 3, low[3] = 3 | |
| 6 | 3 finishes, low == index | pop [5, 4, 3] | |
| 7 | 2, 1 return | low[1] = 0, low[0] = 0 | |
| 8 | 0 finishes, low == index | pop [2, 1, 0] | |
| 9 | discover 6; edge 6→5, 5 off stack | ignored | |
| 10 | discover 7; edge 7→6 on stack | low[7] = 6 | |
| 11 | 6 finishes, low[6] = 6 | pop [7, 6] |
The result [[5, 4, 3], [2, 1, 0], [7, 6]] is in reverse topological order: {6,7} has an edge into {3,4,5}, and so does {0,1,2}.
Checking the invariants mechanically
The script below runs Tarjan's algorithm on random graphs and asserts each fact from this chapter against brute-force reachability.
import random
import sys
sys.setrecursionlimit(10000)
def reach(adj, s):
seen, st = {s}, [s]
while st:
u = st.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
st.append(v)
return seen
def brute_comp_of(n, adj):
R = [reach(adj, u) for u in range(n)]
return {u: frozenset(v for v in range(n) if v in R[u] and u in R[v])
for u in range(n)}
def tarjan_checked(n, adj):
comp_of = brute_comp_of(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])
else:
# Ignored edge: must cross into a different SCC
assert comp_of[w] != comp_of[v]
first = min(index[u] for u in comp_of[v] if index[u] is not None)
is_root = first == index[v]
assert (low[v] == index[v]) == is_root # Fact 3
if is_root:
comp = []
while True:
w = stack.pop()
on_stack[w] = False
comp.append(w)
if w == v:
break
assert frozenset(comp) == comp_of[v] # exactly one SCC
sccs.append(comp)
for v in range(n):
if index[v] is None:
strongconnect(v)
pos = {u: i for i, comp in enumerate(sccs) for u in comp}
for u in range(n):
for v in adj[u]:
if pos[u] != pos[v]:
assert pos[u] > pos[v] # reverse topological order
return sccs
random.seed(1)
for _ in range(2000):
n = random.randint(1, 12)
p = random.random() * 0.4
adj = [[v for v in range(n) if random.random() < p] for _ in range(n)]
tarjan_checked(n, adj)
print(tarjan_checked(8, [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]))
print("all invariant checks passed")Running it prints [[5, 4, 3], [2, 1, 0], [7, 6]] and then the success message. Self-loops and isolated vertices appear among the random graphs and pass as well, since a vertex with no cycle forms an SCC of its own.
Exercise
In the example graph, suppose the line elif on_stack[w]: is changed to elif index[w] is not None:. What happens when vertex 6 is processed?
Show answer
The edge 6→5 now sets low[6] = min(6, index[5]) = 5. After 7 returns, low[6] is still 5, so low[6] != index[6] and 6 does not pass the root test. Because 6 is a top-level DFS root, nothing above it can pop it, so 7 and 6 stay on the stack and their SCC is never output. The ignored-edge argument explains why this edge has to be skipped: 5 sits in a finished SCC that cannot reach 6.
Exercise
The proof that "low[v] < index[v] implies v is not a root" relies on an earlier-discovered on-stack vertex w being able to reach v. Why is this true even when w has already finished?
Show answer
By the stack invariant, a finished vertex still on the stack can reach some active vertex a. Active vertices form the current root-to-v path in the DFS tree, so a is an ancestor of v and reaches v through tree edges. So w reaches a, and a reaches v.
Exercise
Tarjan's algorithm outputs SCC B before SCC A whenever there is an edge from A to B. Using the case where A's root is discovered first, explain why B's root must finish first.
Show answer
When A's root r is discovered, every vertex of B is unvisited and reachable from r through the edge A→B. By the white-path theorem, all of B, including its root, becomes a descendant of r. A descendant finishes before its ancestor, so B's root passes its test and pops B before r pops A.