Tarjan's Algorithm with Low-Links
Kosaraju's algorithm needs two searches and a reversed copy of the graph. Robert Tarjan's algorithm (1972) finds the strongly connected components in a single depth-first search, with no transpose, by keeping one extra number per vertex: its low-link, the earliest vertex it can get back to. It runs in time like Kosaraju, usually does less work in practice, and outputs the components in a useful order, sinks of the component graph first. Compilers, model checkers and package managers use it, and the same low-link idea finds bridges and articulation points in undirected graphs.
Low-links
Number the vertices in the order DFS discovers them: Every component has a unique root, its first-discovered vertex; by the white-path theorem the whole component lies in the root's DFS subtree.
Tarjan's algorithm keeps the vertices of components not yet output on an explicit stack, in discovery order. The low-link of is
computed bottom-up as the search returns. The key fact: is the root of its component exactly when , that is, nothing in 's subtree can climb back above to a vertex whose component is still open. At that moment the component of is precisely and everything above it on the stack.
TARJAN(G)
1 index = 0; S = an empty stack
2 for each vertex u in G.V: if u.index is undefined: STRONGCONNECT(u)
STRONGCONNECT(u)
1 u.index = index; u.low = index; index = index + 1
2 push u on S; u.onstack = TRUE
3 for each v in G.Adj[u]
4 if v.index is undefined // tree edge
5 STRONGCONNECT(v)
6 u.low = min(u.low, v.low)
7 elseif v.onstack // back edge, or cross edge into an open component
8 u.low = min(u.low, v.index)
9 if u.low == u.index // u is the root of a component
10 repeat
11 pop w from S; w.onstack = FALSE; add w to the component
12 until w == u
13 output the componentEdges to vertices that are not on the stack (line 7 fails) lead into components that were already output; they cannot help climb back, so they are ignored.
Watching it work
The graph is the one from the Kosaraju lesson. Tarjan's search follows the same depth-first order, which the animation shows:
The Python version prints every low-link update and every component as it is popped.
adj = {"A": ["B"], "B": ["C", "D"], "C": ["A", "E"], "D": ["E"], "E": ["D", "F"], "F": ["G"], "G": ["H"], "H": ["F"]}
def tarjan(adj):
index, low, on_stack = {}, {}, set()
stack, components = [], []
counter = 0
def connect(u):
nonlocal counter
index[u] = low[u] = counter
counter += 1
stack.append(u); on_stack.add(u)
for v in adj[u]:
if v not in index:
connect(v)
if low[v] < low[u]:
low[u] = low[v]
print(f" {u}: low = {low[u]} (from child {v})")
elif v in on_stack and index[v] < low[u]:
low[u] = index[v]
print(f" {u}: low = {low[u]} (edge to {v}, still on the stack)")
if low[u] == index[u]:
comp = []
while True:
w = stack.pop(); on_stack.discard(w); comp.append(w)
if w == u:
break
components.append(sorted(comp))
print(f"{u} is a root (index = low = {index[u]}): pop {{{', '.join(sorted(comp))}}}")
for u in sorted(adj):
if u not in index:
connect(u)
return components, index, low
components, index, low = tarjan(adj)
print("index:", index)
print("low: ", low)
print("components in output order:", components) C: low = 0 (edge to A, still on the stack)
D: low = 3 (edge to E, still on the stack)
H: low = 5 (edge to F, still on the stack)
G: low = 5 (from child H)
F is a root (index = low = 5): pop {F, G, H}
E is a root (index = low = 3): pop {D, E}
B: low = 0 (from child C)
A is a root (index = low = 0): pop {A, B, C}
index: {'A': 0, 'B': 1, 'C': 2, 'E': 3, 'D': 4, 'F': 5, 'G': 6, 'H': 7}
low: {'A': 0, 'B': 0, 'C': 0, 'E': 3, 'D': 3, 'F': 5, 'G': 5, 'H': 5}
components in output order: [['F', 'G', 'H'], ['D', 'E'], ['A', 'B', 'C']]
The first component completed is the sink : when the search returns to , nothing below it reaches above it, so is a root. 's edge to is a back edge to a vertex still on the stack, so and is not a root; is, and pops . The edge is examined after has been output: is off the stack and the edge is ignored. Finally 's back edge to propagates up through , and pops the source component.
Why it works, in outline
Proof sketch
Invariant. The stack holds exactly the discovered vertices whose component has not been output yet, in discovery order. Each of them belongs to the same component as some vertex on the current DFS path (the gray vertices), because a component is popped as soon as its root finishes.
A root has low = index. If is the root of its component, no vertex of 's subtree has an edge to a stacked vertex discovered before : such a vertex is still open, so it lies on the current DFS path or can reach a vertex on it, which is an ancestor of ; then 's subtree could reach an ancestor of , which can reach (by the tree path), making that ancestor part of 's component and contradicting that is the first-discovered vertex of it.
A non-root has low < index. If is not the root, its component's root is a proper ancestor, and there is a path from back to . The first edge of that path to leave 's subtree goes to a vertex discovered before that is still on the stack (it is in the same component as , which is still open), so line 6 or 8 lowers below .
What gets popped is exactly the component. When root pops, the stack above holds vertices of 's subtree that were not popped earlier, i.e. not in components rooted deeper. They are all in 's component: each could reach back above itself, and the chain of such climbs ends at .
Each vertex is pushed and popped once, and each edge is examined once, so the running time is . Components come out in reverse topological order of the component graph: a component is output only after every component reachable from it.
Agreement with Kosaraju
The program runs both algorithms on 300 random graphs, checks that they find the same partition, and checks the output order: for every edge between two components, Tarjan outputs the target component first.
import random
def tarjan(adj):
n = len(adj)
index, low, on, stack, comps, counter = [-1] * n, [0] * n, [False] * n, [], [], 0
def connect(u):
nonlocal counter
index[u] = low[u] = counter; counter += 1
stack.append(u); on[u] = True
for v in adj[u]:
if index[v] < 0:
connect(v); low[u] = min(low[u], low[v])
elif on[v]:
low[u] = min(low[u], index[v])
if low[u] == index[u]:
comp = set()
while True:
w = stack.pop(); on[w] = False; comp.add(w)
if w == u:
break
comps.append(frozenset(comp))
for u in range(n):
if index[u] < 0:
connect(u)
return comps
def kosaraju(adj):
n, seen, finish = len(adj), set(), []
def v1(u):
seen.add(u)
for v in adj[u]:
if v not in seen: v1(v)
finish.append(u)
for u in range(n):
if u not in seen: v1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]: radj[v].append(u)
comp, groups = {}, []
def v2(u, g):
comp[u] = g; groups[g].add(u)
for v in radj[u]:
if v not in comp: v2(v, g)
for u in reversed(finish):
if u not in comp:
groups.append(set()); v2(u, len(groups) - 1)
return [frozenset(g) for g in groups]
rng = random.Random(23)
order_checks = 0
for trial in range(300):
n = rng.randint(1, 25)
adj = [[v for v in range(n) if v != u and rng.random() < 0.1] for u in range(n)]
t = tarjan(adj)
assert set(t) == set(kosaraju(adj))
pos = {v: i for i, c in enumerate(t) for v in c}
for u in range(n):
for v in adj[u]:
if pos[u] != pos[v]:
assert pos[v] < pos[u] # target component output first
order_checks += 1
print("Tarjan and Kosaraju agree on 300 random graphs")
print(f"reverse topological output order confirmed on {order_checks} inter-component edges")Tarjan and Kosaraju agree on 300 random graphs
reverse topological output order confirmed on 2612 inter-component edges
In C++
The C++ version is a direct translation with index for "undiscovered".
#include <algorithm>
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
int main() {
const std::string names = "ABCDEFGH";
const int n = static_cast<int>(names.size());
std::vector<std::vector<int>> adj = {{1}, {2, 3}, {0, 4}, {4}, {3, 5}, {6}, {7}, {5}};
std::vector<int> index(n, -1), low(n, 0), stack;
std::vector<bool> on(n, false);
int counter = 0;
std::function<void(int)> connect = [&](int u) {
index[u] = low[u] = counter++;
stack.push_back(u);
on[u] = true;
for (int v : adj[u]) {
if (index[v] < 0) { connect(v); low[u] = std::min(low[u], low[v]); }
else if (on[v]) low[u] = std::min(low[u], index[v]);
}
if (low[u] == index[u]) {
std::string comp;
int w;
do {
w = stack.back(); stack.pop_back(); on[w] = false;
comp += names[w];
} while (w != u);
std::sort(comp.begin(), comp.end());
std::printf("component {%s} with root %c\n", comp.c_str(), names[u]);
}
};
for (int u = 0; u < n; ++u) if (index[u] < 0) connect(u);
}component {FGH} with root F
component {DE} with root E
component {ABC} with root A
Test yourself
When does Tarjan's algorithm output a component?
- When a back edge is found
- When the search returns from a vertex with
- After the second DFS
- When the stack is empty
Why are edges to vertices that are no longer on the stack ignored?
- They are tree edges
- They lead into components that were already output, so they cannot connect back to an open vertex
- They are self-loops
- They would make the algorithm quadratic
In which order does Tarjan's algorithm output the components?
- Topological order of the component graph
- Reverse topological order: a component after all components reachable from it
- Alphabetical order
- Decreasing size