Tarjan's Algorithm
Tarjan's method numbers vertices as a depth-first search reaches them and keeps every visited vertex on a stack. Each vertex also tracks the oldest number it can get back to. When a vertex cannot get back to anything older than itself, it is the first vertex of a component, and everything above it on the stack is that component.
One Search Instead of Two
The Tarjan algorithm (Robert Tarjan, 1972) finds the strongly connected components of a directed graph in a single depth-first search. Kosaraju's algorithm needs two searches and a reversed copy of the graph; Tarjan needs neither, at the price of two numbers per vertex and an extra stack. The general idea of a component, and how the two methods compare, is in the strongly connected components lesson.
The example is the same graph as the Kosaraju lesson, so the answers can be checked against each other: 8 vertices and the edges 0 → 1, 1 → 3, 1 → 2, 2 → 0, 2 → 7, 3 → 4, 4 → 3, 4 → 5, 5 → 6, 6 → 5, 7 → 4.
Discovery Time and Low Link Value
A counter starts at 0. When the search first reaches u it sets disc[u] to the counter and adds one. disc never changes after that.
The low link value low[u] starts equal to disc[u] and can only go down. It records the smallest discovery time that u's part of the search tree can get back to, using tree edges down and then one edge to a vertex that is still on the stack. If low[u] stays equal to disc[u], nothing below u can climb above it, which is what marks u as the first vertex, the root, of a component.
- disc[u]: when u was reached
- low[u]: oldest vertex still on the stack that u's subtree can reach
- on_stack[u]: true from when u is pushed until its component is popped
The Steps
- Arrive at u: set disc[u] = low[u] = counter, add one to the counter, push u, mark it on the stack
- For each edge u → v with v unvisited: visit v, then set low[u] = min(low[u], low[v])
- For each edge u → v with v on the stack: set low[u] = min(low[u], disc[v])
- For each edge u → v with v visited but off the stack: do nothing
- Before leaving u: if low[u] == disc[u], pop vertices until u comes off; those vertices are one component
- Repeat from every vertex the search has not reached
Each vertex is visited once. The work happens when the search arrives and again when it is about to leave.
Terms, operations, and practical uses
Key terms
- disc[u]The counter value when the search first reached u.
- low[u]The smallest disc reachable from u's subtree through one edge to a vertex still on the stack.
- Root of a componentThe first vertex of the component the search reached; the one with low == disc.
- On the stackVisited, and its component has not been popped yet.
Related lessons and problems
- Strongly Connected ComponentsThe definition, the component graph, and Kosaraju vs Tarjan.
- Kosaraju's AlgorithmTwo passes and a reversed graph, same components.
- Bridges in a GraphThe low value on an undirected graph, for edges.
- Depth-First SearchThe search the numbers are attached to.
- Strongly Connected Components (problem)Count the components.
Code in Python, C++ and Java
def tarjan(n, adj, check_on_stack=True):
disc = [-1] * n
low = [0] * n
on_stack = [False] * n
stack, components = [], []
clock = 0
def visit(u):
nonlocal clock
disc[u] = low[u] = clock
clock += 1
stack.append(u)
on_stack[u] = True
for v in adj[u]:
if disc[v] == -1:
visit(v)
low[u] = min(low[u], low[v])
elif on_stack[v] or not check_on_stack:
low[u] = min(low[u], disc[v])
if low[u] == disc[u]:
group = []
while True:
w = stack.pop()
on_stack[w] = False
group.append(w)
if w == u:
break
components.append(sorted(group))
for u in range(n):
if disc[u] == -1:
visit(u)
return components, disc, low
edges = [(0, 1), (1, 3), (1, 2), (2, 0), (2, 7), (3, 4), (4, 3), (4, 5), (5, 6), (6, 5), (7, 4)]
n = 8
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
components, disc, low = tarjan(n, adj)
print("disc:", disc)
print("low: ", low)
print("components in the order found:", components)
wrong, _, low = tarjan(n, adj, check_on_stack=False)
print("without the on-stack check:", wrong, "low[7] =", low[7])
print("self-loop on one vertex:", tarjan(1, [[0]])[0])
print("no edges:", tarjan(3, [[], [], []])[0])#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Graph = vector<vector<int>>;
struct Tarjan {
const Graph& adj;
bool checkOnStack;
vector<int> disc, low, stack;
vector<bool> onStack;
vector<vector<int>> components;
int clock = 0;
Tarjan(const Graph& g, bool check = true)
: adj(g), checkOnStack(check), disc(g.size(), -1), low(g.size(), 0), onStack(g.size(), false) {
for (int u = 0; u < (int)g.size(); u++)
if (disc[u] == -1) visit(u);
}
void visit(int u) {
disc[u] = low[u] = clock++;
stack.push_back(u);
onStack[u] = true;
for (int v : adj[u]) {
if (disc[v] == -1) {
visit(v);
low[u] = min(low[u], low[v]);
} else if (onStack[v] || !checkOnStack) {
low[u] = min(low[u], disc[v]);
}
}
if (low[u] == disc[u]) {
vector<int> group;
while (true) {
int w = stack.back();
stack.pop_back();
onStack[w] = false;
group.push_back(w);
if (w == u) break;
}
sort(group.begin(), group.end());
components.push_back(group);
}
}
};
string show(const vector<int>& v) {
string s = "[";
for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
return s + "]";
}
string show(const vector<vector<int>>& g) {
string s = "[";
for (size_t i = 0; i < g.size(); i++) s += (i ? ", " : "") + show(g[i]);
return s + "]";
}
int main() {
vector<pair<int, int>> edges = {{0, 1}, {1, 3}, {1, 2}, {2, 0}, {2, 7}, {3, 4}, {4, 3}, {4, 5}, {5, 6}, {6, 5}, {7, 4}};
Graph adj(8);
for (auto [u, v] : edges) adj[u].push_back(v);
Tarjan t(adj);
cout << "disc: " << show(t.disc) << "\n";
cout << "low: " << show(t.low) << "\n";
cout << "components in the order found: " << show(t.components) << "\n";
Tarjan w(adj, false);
cout << "without the on-stack check: " << show(w.components) << " low[7] = " << w.low[7] << "\n";
Graph loop = {{0}}, empty(3);
cout << "self-loop on one vertex: " << show(Tarjan(loop).components) << "\n";
cout << "no edges: " << show(Tarjan(empty).components) << "\n";
}import java.util.*;
public class Main {
static List<List<Integer>> adj;
static boolean checkOnStack;
static int[] disc, low;
static boolean[] onStack;
static Deque<Integer> stack;
static List<List<Integer>> components;
static int clock;
static List<List<Integer>> tarjan(List<List<Integer>> g, boolean check) {
int n = g.size();
adj = g;
checkOnStack = check;
disc = new int[n];
low = new int[n];
onStack = new boolean[n];
Arrays.fill(disc, -1);
stack = new ArrayDeque<>();
components = new ArrayList<>();
clock = 0;
for (int u = 0; u < n; u++)
if (disc[u] == -1) visit(u);
return components;
}
static void visit(int u) {
disc[u] = low[u] = clock++;
stack.push(u);
onStack[u] = true;
for (int v : adj.get(u)) {
if (disc[v] == -1) {
visit(v);
low[u] = Math.min(low[u], low[v]);
} else if (onStack[v] || !checkOnStack) {
low[u] = Math.min(low[u], disc[v]);
}
}
if (low[u] == disc[u]) {
List<Integer> group = new ArrayList<>();
while (true) {
int w = stack.pop();
onStack[w] = false;
group.add(w);
if (w == u) break;
}
Collections.sort(group);
components.add(group);
}
}
static List<List<Integer>> graph(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
for (int[] e : edges) g.get(e[0]).add(e[1]);
return g;
}
public static void main(String[] args) {
int[][] edges = {{0, 1}, {1, 3}, {1, 2}, {2, 0}, {2, 7}, {3, 4}, {4, 3}, {4, 5}, {5, 6}, {6, 5}, {7, 4}};
List<List<Integer>> g = graph(8, edges);
List<List<Integer>> found = tarjan(g, true);
System.out.println("disc: " + Arrays.toString(disc));
System.out.println("low: " + Arrays.toString(low));
System.out.println("components in the order found: " + found);
List<List<Integer>> wrong = tarjan(g, false);
System.out.println("without the on-stack check: " + wrong + " low[7] = " + low[7]);
System.out.println("self-loop on one vertex: " + tarjan(graph(1, new int[][]{{0, 0}}), true));
System.out.println("no edges: " + tarjan(graph(3, new int[][]{}), true));
}
}Step through it
Running on 0→1, 1→3, 1→2, 2→0, 2→7, 3→4, 4→3, 4→5, 5→6, 6→5, 7→4
Worked Example
From 0 the search reaches 0, 1, 3, 4, 5, 6 with disc 0 to 5. The edge 6 → 5 points at 5, which is on the stack, so low[6] drops to 4. Leaving 6, low[6] = 4 is not disc[6] = 5, so 6 stays. Leaving 5, low[5] = disc[5] = 4: pop 6 and 5, the first component {5, 6}.
Before that, 4 → 3 had lowered low[4] to 2. 4 stays when the search leaves it; 3 then has low[3] = disc[3] = 2, so 4 and 3 come off as {3, 4}. Back at 1, the search tries 2 (disc 6). 2 → 0 lowers low[2] to 0. 2 → 7 visits 7 (disc 7), whose only edge 7 → 4 points at a vertex already popped, so nothing changes and 7 is its own component {7}. Finally 2 and 1 inherit low 0, and 0 pops {0, 1, 2}.
- disc = 0, 1, 6, 2, 3, 4, 5, 7 and low = 0, 0, 0, 2, 2, 4, 4, 7 for vertices 0 to 7
- Found in the order {5, 6}, {3, 4}, {7}, {0, 1, 2}
- Kosaraju found the same four in the order {0, 1, 2}, {7}, {3, 4}, {5, 6}
Why the On-Stack Check Matters
The edge 7 → 4 leads to a vertex that has been visited but is no longer on the stack. Vertex 4 belongs to a component that is already complete, and 4 cannot reach 7 (or the search from 4 would have found 7 first). Such an edge can never be part of a cycle through 7, so it must not lower low[7].
Drop the check and treat every visited vertex alike. low[7] becomes disc[4] = 3, which is less than disc[7] = 7, so 7 is not treated as a root and stays on the stack. It is popped later together with 0, 1 and 2, giving the wrong component {0, 1, 2, 7}. The code on this page prints exactly this when the check is turned off.
Why low == disc Marks a Component
Everything above u on the stack was reached from u, so u reaches all of it. If one of those vertices could reach a vertex below u that is still on the stack, its low value would be smaller than disc[u] and would have been passed up to u. low[u] == disc[u] says that never happened: no vertex above u gets out to anything older. And every vertex above u that could not reach back to u would already have been popped as the root of its own component. So the vertices from u to the top are exactly the ones that reach u and that u reaches.
A component is popped only after every component it points to has been popped, because the search finishes those first. So the order of output is a reverse topological order of the component graph: sinks first, sources last. That suits dynamic programming that needs the answers of successors first, such as counting how many vertices each component can reach.
- Some versions write min(low[u], low[v]) for on-stack edges too; the roots, and so the components, stay the same, but low no longer matches its definition
- That shortcut is not safe in the cut-vertex test, which reads the numbers themselves
Iterative Tarjan Algorithm and Cost
Each vertex is pushed once and popped once, and each edge is looked at once, so the running time is O(V + E) on adjacency lists. Extra memory is O(V): disc, low, the on-stack flags and the stack. No transpose is built, which is Tarjan's main practical advantage over Kosaraju on large graphs.
The recursive version is short, but a path of 100,000 vertices means 100,000 nested calls. An iterative tarjan algorithm keeps its own stack of frames, each holding a vertex and the index of its next edge. When a child frame finishes, the parent reads the child's low before moving on; that hand-back is the only part that needs care, and forgetting it leaves low[u] too high and splits components.
- Time O(V + E), memory O(V) on top of the graph
- Iterative frames: (vertex, next edge index); on return, low[parent] = min(low[parent], low[child])
- A vertex with a self-loop is still one component of size 1
Related Ideas and Problems
The same discovery time and low value appear in the undirected searches for bridges in a graph and for articulation points. There every visited vertex is an ancestor or a descendant, so no stack of open vertices is needed; the low value alone answers the question.
- Strongly Connected Components (Kosaraju): the count, which Tarjan also gives
- Course Schedule II: an order exists only if every component has one vertex