Tarjan’s algorithm for strongly connected components
Strongly connected components (SCCs) are maximal groups of vertices in a directed graph where every vertex can reach every other vertex. They expose circular structure that a plain reachability search can blur. If a vertex is a task and an edge means “must happen before”, an SCC identifies tasks that depend on one another and therefore cannot be scheduled independently.
Tarjan’s algorithm finds every SCC in linear time with one depth-first search. It combines discovery indices, low-link values and an explicit stack, making it both efficient and conceptually rich. This tutorial develops the bookkeeping, presents pseudocode and Python, then compares Tarjan’s method with alternatives commonly encountered in graph-based engineering work.
Why strongly connected components matter
A simple example shows why reachability and connectivity differ. Consider edges 0→1, 0→2, 1→2, 2→0, 2→3, 3→4, 4→5 and 5→3. Vertices 0, 1 and 2 form one SCC: each can reach the others. Vertices 3, 4 and 5 form another. Vertex 2 can reach vertex 3, but the reverse path does not exist, so the two groups remain separate.
The representation also has practical value in Australian settings. Transport networks in Sydney and Melbourne contain one-way links, while Brisbane’s bike and road maps add turn and access constraints. Because road traffic in Australia keeps to the left, edge direction is a modelling concern rather than cosmetic detail. Resource operators in the Pilbara can analyse haul-route dependencies, and businesses in Australia’s e-commerce and fintech market use directed graphs for settlement, refunds and reconciliation. Emergency mapping for bushfires presents another network-shaped problem. Each case asks which parts of a system lock together.
The ideas behind Tarjan’s traversal
During the depth-first search, index[v] records when vertex v was first discovered. low[v] records the smallest discovery index reachable by descending through DFS-tree edges and then taking at most one edge to a vertex still on the active stack. For a tree child w, the child’s low-link is folded into its parent. For an edge to an already discovered neighbour w, the parent uses index[w] only when w remains on the stack.
The active stack contains vertices found by the search but not yet assigned to a completed component. When low[v] == index[v], no vertex in v’s remaining DFS subtree can connect back to an earlier active ancestor. The algorithm can therefore pop vertices through v, and that popped run is one SCC. A vertex with a smaller low-link stays on the stack because it belongs to a component extending toward an ancestor.
DFS(v):
index[v] = next_index
low[v] = index[v]
next_index = next_index + 1
push v onto the active stack
for each neighbour w of v:
if w has no index:
DFS(w)
low[v] = min(low[v], low[w])
else if w is on the active stack:
low[v] = min(low[v], index[w])
if low[v] == index[v]:
pop vertices through v
return them as one strongly connected component
The crucial invariant is that a stack edge updates low with a discovery index, while a tree edge updates it with a child’s low-link. Every vertex is pushed and popped once, and every edge is examined once. The search therefore takes O(V + E) time, with O(V) auxiliary space beyond the graph. Condensing the SCCs produces a directed acyclic graph that can support topological sorting or further analysis.
A practical Python implementation
The following implementation accepts an adjacency mapping. It uses closures to retain the traversal state and returns the discovered components as lists.
def strongly_connected_components(graph):
index = {}
low = {}
stack = []
on_stack = set()
components = []
next_index = 0
def dfs(vertex):
nonlocal next_index
index[vertex] = next_index
low[vertex] = next_index
next_index += 1
stack.append(vertex)
on_stack.add(vertex)
for neighbour in graph.get(vertex, ()):
if neighbour not in index:
dfs(neighbour)
low[vertex] = min(low[vertex], low[neighbour])
elif neighbour in on_stack:
low[vertex] = min(low[vertex], index[neighbour])
if low[vertex] == index[vertex]:
component = []
while True:
member = stack.pop()
on_stack.remove(member)
component.append(member)
if member == vertex:
break
components.append(component)
for vertex in graph:
if vertex not in index:
dfs(vertex)
return components
sample_graph = {
0: [1, 2],
1: [2],
2: [0, 3],
3: [4],
4: [5],
5: [3],
}
result = strongly_connected_components(sample_graph)
For the sample, the result contains the groups {0, 1, 2} and {3, 4, 5}. Their order within each list depends on the traversal and should not be treated as significant. The function also handles isolated vertices, self-loops and destinations that appear as neighbours without being dictionary keys.
Python’s recursive call stack can become a limitation on a long chain of vertices. An iterative implementation is safer for very deep graphs, while changing recursion limits should be based on measured depth rather than guesswork. Readers who want a broader refresher can use the Python programming collection to revisit dictionaries, sets, closures and recursion before adapting the function.
Comparing strongly connected component algorithms
Tarjan, Kosaraju and Gabow all run in O(V + E), but they organise the traversal differently:
| Method | DFS passes | Extra structures | Useful when |
|---|---|---|---|
| Tarjan | One | Discovery index, low-link values, active stack | A single traversal and compact auxiliary state are preferred |
| Kosaraju | Two, using original and reversed graphs | Visited flags, finish-order stack, transpose | Clear implementation and debugging matter most |
| Gabow | One | Discovery index and two stacks | Path-based component extraction suits the application |
Kosaraju is often easier to explain because it pairs DFS finishing order with a reverse graph. Tarjan avoids materialising that transpose and encodes the dependency through low-link values. Gabow replaces low-link arithmetic with a second stack and a common-path structure. The result is equivalent when the input graph and edge directions are identical.
Choose the method according to team familiarity, graph mutability and memory limits rather than small constant-factor differences. If an application stores neighbours in a custom map, an open addressing hash table can provide constant-time average lookup, although the SCC algorithm retains its O(V + E) bound and conventional adjacency lists are usually clearer.
Practical guidance for dependable implementations
These recommendations keep the implementation aligned with real graph-processing pipelines:
- Document the direction of every edge and confirm that reverse dependencies are represented explicitly.
- Prefer adjacency lists for traversal-heavy graphs because they provide efficient access to outgoing neighbours.
- Use stable, hashable vertex identifiers so dictionary lookups and set membership remain predictable.
- Handle isolated vertices and self-loops deliberately, since both can expose assumptions in component extraction.
- Keep component ordering out of public contracts unless a deterministic ordering is genuinely required.
- Test with small, hand-checked graphs before stress-testing long chains, dense edges and large SCCs.
Tarjan is often one part of a wider algorithmic toolkit. For contrast, the dynamic programming guide solves longest common subsequence with a two-dimensional grid, showing how a different method removes repeated work through stored subproblem values. Once Tarjan condenses SCCs into a directed acyclic graph, topological sorting, reachability analysis and dynamic programming can operate on that simpler structure. This combination of linear-time decomposition and graph-level reasoning makes Tarjan a durable building block for dependency analysis, scheduling and directed-network software.