Strongly Connected Components: Tarjan & Kosaraju
Two linear-time algorithms, and why they work.
Tarjan's 1972 algorithm finds every strongly connected component of a directed graph in a single depth-first search, emitting each component the moment the search leaves it for good. Kosaraju's two-pass algorithm is easier to state, but why it works is subtler. Both rest on one lemma about when DFS finishes the vertices of different components.
What you’ll learn
- State and prove the finishing-time lemma for strongly connected components, and derive from it the correctness of the Kosaraju–Sharir algorithm.
- Define low-link values precisely and prove Tarjan's root test: a vertex is the first of its component exactly when its low-link equals its discovery index.
- Implement both algorithms in , explain why edges into finished components must be ignored, and know which topological order of the condensation each one produces.
- Describe the path-based method, and the state of the art for strong connectivity in dynamic and parallel settings.
One lemma about finishing times
Case . Let be the first vertex of discovered. At time , all of is white, and all of it is reachable from : inside , then across the edge into . By the white-path theorem, every vertex of becomes a descendant of and finishes before :
Case . Let be the first vertex of discovered. All of becomes descendants of , so . No vertex of is reachable from , since otherwise the two components would reach each other and be one. So is still white when finishes, and is discovered only later:
Corollary. The vertex that finishes last lies in a source component of the condensation, one that no edge enters: an edge into its component would give a later finishing time.
After a complete DFS of , in which component of the condensation does the vertex with the largest finishing time lie?
- A source component: no edge enters it
- A sink component: no edge leaves it
- The component of the vertex where the DFS started
- The component with the most vertices
Show the answer
A. A source component: no edge enters it
If an edge entered the last finisher's component from a component , the lemma would give , contradicting that holds the largest finishing time. This holds wherever the search starts, which is what makes Kosaraju's second pass work.
Kosaraju–Sharir: two passes
S. Rao Kosaraju found the algorithm in 1978 but did not publish it; Micha Sharir published it independently in 1981. Kosaraju's algorithm makes two passes:
- Run DFS on and list the vertices in order of finishing.
- Reverse every edge. The reversed graph has exactly the same components.
- Scan the list from the last finisher backward. Whenever the scanned vertex is unassigned, search from it; the unassigned vertices it reaches form one component.
Suppose the first searches each produced one whole component, and the next search starts at , the unassigned vertex with the largest finishing time. Its component is entirely unassigned, and it has the largest finishing time among the components not yet found:
The search covers . is strongly connected in as well, and all of it is unassigned, so the search from reaches all of it.
It covers nothing else. An edge of leaving toward a component is an edge of . By the lemma , so by the choice of , was already found and its vertices are assigned:
Topological order. The same step shows that every component with an edge into is found before . So the components come out sources first:
def kosaraju(n, adj):
"""Component id per vertex; ids follow a topological order of the condensation."""
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
seen, order = [False] * n, [] # pass 1: finishing order on G
for s in range(n):
if seen[s]:
continue
seen[s] = True
stack = [(s, iter(adj[s]))]
while stack:
u, it = stack[-1]
v = next((w for w in it if not seen[w]), None)
if v is None:
order.append(u) # u finishes
stack.pop()
else:
seen[v] = True
stack.append((v, iter(adj[v])))
comp, c = [-1] * n, 0 # pass 2: reversed graph, latest finisher first
for s in reversed(order):
if comp[s] == -1:
comp[s], stack = c, [s]
while stack:
u = stack.pop()
for v in radj[u]:
if comp[v] == -1:
comp[v] = c
stack.append(v)
c += 1
return compExplicit stacks keep deep graphs safe: the first pass resumes each vertex's neighbor iterator where it stopped. time and memory, but the algorithm builds and scans every edge twice. The second pass may use any search, BFS included, since it only needs to collect what is reachable.
Tarjan: one pass with low-links
Tarjan's algorithm (1972) needs neither the reversed graph nor a second pass. Number the vertices in discovery order, , and push each vertex onto a stack when it is discovered. A vertex leaves only once its whole component has been identified, so always holds exactly the discovered vertices not yet assigned to a component. Each component is identified at its root, the first of its vertices that DFS discovers.
A root has . Suppose an edge from 's subtree reaches a vertex with . Since is unassigned, the root of its component has not returned, so is on the recursion stack, an ancestor of ; and makes it a proper ancestor of . Then and lie on a common cycle, so is not the root of its component:
A non-root has . The root of 's component is a proper ancestor of , and some path leads from to . Let be its first edge that leaves 's subtree. If were white when scanned, it would become a descendant of ; and a vertex discovered while is active is 's descendant. So was discovered before . It lies in 's unfinished component, hence on :
Exactly the component is popped. When root returns, every vertex above it on was discovered during 's call, so it is a descendant of . A descendant whose component root is a proper descendant of was popped when that root returned. So everything above is in 's component, and conversely every vertex of the component is a descendant of (white-path theorem) that is still waiting on :
import sys
def tarjan(n, adj):
"""Component id per vertex; ids follow a REVERSE topological order (sinks first)."""
sys.setrecursionlimit(10_000 + 2 * n)
disc, low = [-1] * n, [0] * n
on_stack, stack, comp = [False] * n, [], [-1] * n
timer = count = 0
def visit(u):
nonlocal timer, count
disc[u] = low[u] = timer
timer += 1
stack.append(u)
on_stack[u] = True
for v in adj[u]:
if disc[v] == -1: # tree edge
visit(v)
low[u] = min(low[u], low[v])
elif on_stack[v]: # edge into an unfinished component
low[u] = min(low[u], disc[v])
if low[u] == disc[u]: # u is the root of its component
while True:
v = stack.pop()
on_stack[v] = False
comp[v] = count
if v == u:
break
count += 1
for u in range(n):
if disc[u] == -1:
visit(u)
return comp: each vertex is pushed and popped once and each edge scanned once. Components are numbered as they are popped, sinks first, because a component is popped only after every component it can reach.
Trace it on the graph with edges , , , , , , , , , , and , starting at and scanning neighbors alphabetically:
| Vertex | disc | low | Component (popped) |
|---|---|---|---|
| 0 | 0 | (4th) | |
| 1 | 0 | ||
| 2 | 0 | ||
| 3 | 3 | (2nd) | |
| 4 | 4 | (1st) | |
| 5 | 4 | ||
| 6 | 6 | (3rd) | |
| 7 | 6 | ||
| 8 | 6 |
In this trace, suppose a buggy version drops the on-stack test and lowers to when it scans . What happens?
- Nothing changes: the value 5 never decides a root test
- is split into two components
- drops to 5, below , so is never recognized as a root and is merged into
- The algorithm never terminates
Show the answer
C. drops to 5, below , so is never recognized as a root and is merged into
With the bug, and then , so stay on the stack until returns and pops through as one "component". The output becomes . The on-stack test is what limits low-links to unfinished components.
Path-based search, and the frontier
A third family keeps no low-links. While DFS walks down a path, an edge back to an unassigned vertex proves that the whole stretch of the path from to the current vertex lies in one component, so those vertices can be merged into one tentative component. Two stacks suffice: holds the unassigned vertices in discovery order, and holds the first vertex of each tentative component along the current path. The idea goes back to Purdom (1970) and Munro (1971); Dijkstra (1976) gave the first linear-time version, and Cheriyan & Mehlhorn (1996) and Gabow (2000) the modern form.
PATH-BASED-SCC(G): # Gabow (2000)
counter ← 0; S ← empty stack; P ← empty stack
for each vertex v: pre[v] ← undefined
for each vertex v with pre[v] undefined: VISIT(v)
VISIT(v):
pre[v] ← counter; counter ← counter + 1
push v onto S; push v onto P
for each edge v → w:
if pre[w] is undefined:
VISIT(w)
else if w is not yet assigned to a component:
while pre[top(P)] > pre[w]: pop P # merge the cycle through w
if top(P) = v: # v is the first vertex of a component
pop P
pop S down to and including v; output those vertices as one componentLinear time, components emitted sinks first as in Tarjan's algorithm; the only number stored per vertex is its preorder index.
| Algorithm | DFS passes | Extra data | Components emitted |
|---|---|---|---|
| Kosaraju–Sharir | 2, on and on | visited flags, finishing order, the reversed graph | sources first |
| Tarjan | 1 | discovery index, low-link and on-stack flag per vertex | sinks first |
| Path-based (Gabow) | 1 | preorder index per vertex, two stacks | sinks first |
Collapse, then solve a DAG. Many problems on general directed graphs become DAG problems on the condensation. To collect as much value as possible on a walk that may repeat vertices, give each component the total value of its vertices (a walk that enters a component can visit all of it and leave from any vertex), then find a heaviest path in the condensation by dynamic programming in topological order. Reachability reduces the same way, since all vertices of a component reach the same set. The next Optimal lesson, 2-SAT, decides Boolean formulas this way.
Key takeaways
- If an edge leads from component to component , then ; so the last vertex to finish lies in a source component.
- Kosaraju–Sharir: DFS on for finishing times, then searches on from the latest unassigned finisher; each search is one component, found in topological order, in .
- Tarjan: one DFS with a stack and low-links; starts a component exactly when ; edges into already-popped components must be ignored; components come out sinks first.
- The path-based method (Dijkstra 1976; Cheriyan & Mehlhorn 1996; Gabow 2000) replaces low-links with a stack of tentative component boundaries, also in linear time.
- Strong connectivity under edge deletions has near-linear total update time (2019), while parallel algorithms remain limited by the cost of parallel reachability.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A dynamic program must process the components of a graph sources first, and you computed the components with Tarjan's algorithm. What order should the program use?
- The order in which Tarjan's algorithm popped the components
- The components sorted by their smallest discovery time
- The reverse of the order in which the components were popped
- The components sorted by size, largest first
Show the answer
C. The reverse of the order in which the components were popped
Tarjan's algorithm pops a component only after every component it can reach has been popped, so popping order is a reverse topological order: sinks first. Reversing it gives sources first, at no extra cost. (Kosaraju's algorithm produces sources first directly.)
In Tarjan's algorithm, vertex 's call is about to return and . What follows?
- is the first vertex of its component, which is popped now
- shares its component with a proper ancestor, so it stays on the stack
- 's component consists of alone
- cannot reach any vertex discovered before it
Show the answer
B. shares its component with a proper ancestor, so it stays on the stack
means 's subtree reaches an earlier-discovered vertex of an unfinished component, which (by the root test) lies in 's own component. So is not its component's root; it stays on the stack until that root returns.
A proposed shortcut for Kosaraju's algorithm: skip the reversed graph, and run the second pass on itself, starting from the vertex with the smallest finishing time. Does it find the components?
- Yes: the earliest finisher always lies in a sink component, so a search from it cannot leave its component
- Yes, provided the first DFS starts in a source component
- No: a search in started inside a sink component still escapes into other components
- No: the earliest finisher need not lie in a sink component
Show the answer
D. No: the earliest finisher need not lie in a sink component
The lemma orders the latest finishing time of each component, not the earliest. With edges , , and a DFS from that visits first, finishes first, yet its component has an edge to , and a search from in collects all three vertices.
Why do parallel algorithms for strongly connected components avoid depth-first search?
- DFS needs more than linear memory
- Computing the lexicographically first DFS order is P-complete, so no polylogarithmic-depth parallel algorithm for it is expected
- DFS gives wrong answers on graphs with cycles
- Tarjan's algorithm takes quadratic time on dense graphs
Show the answer
B. Computing the lexicographically first DFS order is P-complete, so no polylogarithmic-depth parallel algorithm for it is expected
Reif (1985) showed that the lexicographically first DFS order is P-complete, so it has no polylogarithmic-depth algorithm unless every polynomial-time problem does (NC = P). Parallel SCC algorithms are built on reachability searches instead.
Further reading
- R. E. Tarjan, "Depth-first search and linear graph algorithms," SIAM Journal on Computing 1(2) (1972), 146–160.
- M. Sharir, "A strong-connectivity algorithm and its applications in data flow analysis," Computers & Mathematics with Applications 7(1) (1981), 67–72.
- H. N. Gabow, "Path-based depth-first search for strong and biconnected components," Information Processing Letters 74(3–4) (2000), 107–114.
- A. Bernstein, M. Probst Gutenberg & C. Wulff-Nilsen, "Decremental strongly-connected components and single-source reachability in near-linear time," STOC (2019).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §20.5.