Tarjan
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Tarjan's algorithm finds strongly connected groups in one single walk, by numbering nodes as they are discovered and noting the oldest numbered node each can get back to. It is quick and also the base for finding weak points in networks.
Practical use cases
- Web app: Recursive function groups in a code analyser. A code-quality tool shows which functions call each other in circles, which is mutual recursion. One walk of the call graph labels each group in a single pass, which is fast enough to run on every commit. The team gets the warning in the pull request without slowing the build.
- Web app: Dependency knots in a package registry. A package website shows "circular dependency detected" with the exact packages in the loop. Finding all knots at once helps maintainers fix them together.
- Web app: Game level graph. A level editor links rooms by one-way doors. Tarjan finds sets of rooms a player can wander freely between, and spots rooms that are traps from which you cannot return. This helps designers balance levels without lots of manual play-testing.
- System: Compilers, linkers and logic solvers. Compilers use it to find groups of declarations that depend on each other, which must be handled together. The single walk with numbering is what makes the method fast enough for large programs with thousands of declarations and calls between them.
The story: Zoya and the Breadcrumb Trail
Zoya went to explore a maze of one-way lanes with a bag of numbered breadcrumbs. At every new junction she dropped a crumb with the next number (1, 2, 3...): the discovery number. She also kept a rucksack, the stack, where she put every junction she had visited but not yet sorted into a family.
At each junction she asked: "What is the oldest crumb I can reach from here, even by going round a loop?" She wrote that tiny number beside the crumb. This was the low number. If a lane led back to a junction still in her rucksack, she took its crumb number as a candidate for the low.
The great moment came when she finished exploring a junction and found its low number was equal to its own crumb number. "I cannot get back to anything older than myself," she realised, "so I am the head of a family." She emptied the rucksack down to that junction, and everyone she poured out belonged to the same family.
That is Tarjan's algorithm, named after Robert Tarjan. It finds all strongly connected components in a single DFS: no flipping of arrows, only discovery numbers, low numbers and a stack.
How to spot this problem, and where you need it
You need strongly connected groups on a large directed network and want a single pass with no need to build a reversed copy of the data.
Signs you need it
- The network is large or memory is tight, so building a reversed graph feels wasteful.
- You need groups plus a sense of "which node is the oldest in the loop", for example to pick a representative.
- The code is a recursive DFS and you can add a counter and a stack without much change.
Where to use it in a project
- Linters and analysers that run on every build and need fast cycle-group reports.
- Level or workflow editors that warn about areas players or items cannot leave.
The solution
Run DFS and give each node a discovery number plus a "low" number, the smallest discovery number it can reach through its subtree and one back-link. Push nodes onto a stack as you enter them. When you finish a node whose low number equals its own discovery number, it is the head of a group: pop the stack down to this node, and those popped nodes are one strongly connected component.
Payoff: Before: two full passes and a copied graph. After: one pass finds all groups for a 100,000-node graph in a blink.
Explain it like I am 8
You walk through a maze dropping numbered stones. Each time you finish a spot, ask: "can I get back to an older stone than my own?" If not, you are the boss of a family: everyone you saved in your bag since you arrived joins your family.
How it works, step by step
- Run a DFS. On arriving at a node give it a discovery number and set low = discovery. Push it on a stack.
- For every road to a new node: DFS into it, then set
low = min(low, child's low). - For every road to a node that is still on the stack: set
low = min(low, that node's discovery). (A node that is already off the stack belongs to a finished family; ignore it.) - When finished with a node and
low == discovery, it is the head of a component. - Pop the stack until you pop that node. Everything popped is one strongly connected component.
The code in four languages
PHP
<?php
// Tarjan's algorithm: one DFS, a stack, and "low" numbers
function tarjan(array $adj): array {
$n = count($adj);
$disc = array_fill(0, $n, -1); // discovery number (-1 = not seen)
$low = array_fill(0, $n, 0); // oldest discovery number we can get back to
$onStack = array_fill(0, $n, false);
$stack = [];
$groups = [];
$time = 0;
$visit = function (int $u) use (&$visit, &$disc, &$low, &$onStack, &$stack, &$groups, &$time, $adj): void {
$disc[$u] = $low[$u] = $time++;
$stack[] = $u;
$onStack[$u] = true;
foreach ($adj[$u] as $v) {
if ($disc[$v] < 0) { // new junction: explore it
$visit($v);
$low[$u] = min($low[$u], $low[$v]);
} elseif ($onStack[$v]) { // old junction still waiting
$low[$u] = min($low[$u], $disc[$v]);
}
}
if ($low[$u] === $disc[$u]) { // u is the head of a family
$group = [];
do {
$w = array_pop($stack);
$onStack[$w] = false;
$group[] = $w;
} while ($w !== $u);
sort($group);
$groups[] = $group;
}
};
for ($i = 0; $i < $n; $i++) if ($disc[$i] < 0) $visit($i);
return $groups;
}
// junctions 1..6 become 0..5
$adj = [[1], [2], [0, 3], [4], [3, 5], []];
echo json_encode(tarjan($adj)) . PHP_EOL;JavaScript
// Tarjan's algorithm: one DFS, a stack, and "low" numbers
function tarjan(adj) {
const n = adj.length;
const disc = new Array(n).fill(-1); // discovery number (-1 = not seen)
const low = new Array(n).fill(0); // oldest discovery number we can get back to
const onStack = new Array(n).fill(false);
const stack = [];
const groups = [];
let time = 0;
function visit(u) {
disc[u] = low[u] = time++;
stack.push(u);
onStack[u] = true;
for (const v of adj[u]) {
if (disc[v] < 0) { // new junction: explore it
visit(v);
low[u] = Math.min(low[u], low[v]);
} else if (onStack[v]) { // old junction still waiting
low[u] = Math.min(low[u], disc[v]);
}
}
if (low[u] === disc[u]) { // u is the head of a family
const group = [];
let w;
do {
w = stack.pop();
onStack[w] = false;
group.push(w);
} while (w !== u);
groups.push(group.sort((a, b) => a - b));
}
}
for (let i = 0; i < n; i++) if (disc[i] < 0) visit(i);
return groups;
}
// junctions 1..6 become 0..5
const adj = [[1], [2], [0, 3], [4], [3, 5], []];
console.log(JSON.stringify(tarjan(adj)));Java
import java.util.*;
public class Main {
static int[][] adj;
static int[] disc, low; // disc: discovery number (-1 = not seen)
static boolean[] onStack; // low: oldest discovery number we can get back to
static Deque<Integer> stack = new ArrayDeque<>();
static List<List<Integer>> groups = new ArrayList<>();
static int time = 0;
static void visit(int u) {
disc[u] = low[u] = time++;
stack.push(u);
onStack[u] = true;
for (int v : adj[u]) {
if (disc[v] < 0) { // new junction: explore it
visit(v);
low[u] = Math.min(low[u], low[v]);
} else if (onStack[v]) { // old junction still waiting
low[u] = Math.min(low[u], disc[v]);
}
}
if (low[u] == disc[u]) { // u is the head of a family
List<Integer> group = new ArrayList<>();
int w;
do {
w = stack.pop();
onStack[w] = false;
group.add(w);
} while (w != u);
Collections.sort(group);
groups.add(group);
}
}
// Tarjan's algorithm: one DFS, a stack, and "low" numbers
static List<List<Integer>> tarjan(int[][] graph) {
adj = graph;
int n = graph.length;
disc = new int[n];
Arrays.fill(disc, -1);
low = new int[n];
onStack = new boolean[n];
for (int i = 0; i < n; i++) if (disc[i] < 0) visit(i);
return groups;
}
public static void main(String[] args) {
// junctions 1..6 become 0..5
int[][] graph = {{1}, {2}, {0, 3}, {4}, {3, 5}, {}};
System.out.println(tarjan(graph));
}
}Go
package main
import (
"fmt"
"sort"
)
// tarjan's algorithm: one DFS, a stack, and "low" numbers.
func tarjan(adj [][]int) [][]int {
n := len(adj)
disc := make([]int, n) // discovery number (-1 = not seen)
for i := range disc {
disc[i] = -1
}
low := make([]int, n) // oldest discovery number we can get back to
onStack := make([]bool, n)
var stack []int
var groups [][]int
time := 0
var visit func(u int)
visit = func(u int) {
disc[u], low[u] = time, time
time++
stack = append(stack, u)
onStack[u] = true
for _, v := range adj[u] {
if disc[v] < 0 { // new junction: explore it
visit(v)
low[u] = min(low[u], low[v])
} else if onStack[v] { // old junction still waiting
low[u] = min(low[u], disc[v])
}
}
if low[u] == disc[u] { // u is the head of a family
var group []int
for {
w := stack[len(stack)-1]
stack = stack[:len(stack)-1]
onStack[w] = false
group = append(group, w)
if w == u {
break
}
}
sort.Ints(group)
groups = append(groups, group)
}
}
for i := 0; i < n; i++ {
if disc[i] < 0 {
visit(i)
}
}
return groups
}
func main() {
// junctions 1..6 become 0..5
adj := [][]int{{1}, {2}, {0, 3}, {4}, {3, 5}, {}}
fmt.Println(tarjan(adj))
}Time: O(V + E) · Extra space: O(V). A single DFS: each node is pushed and popped once and each road is looked at once.
Watch out for
- Using a finished node's discovery number to lower
low. Only nodes still on the stack may do that. - Comparing
low[u]withlow[v]for a back road. For back roads usedisc[v], and for tree children uselow[v]. - Forgetting the outer loop over all nodes, so unreachable parts of the graph never get visited.
Quick check
- When is a node the "head" of a component in Tarjan?
- When it has the most roads
- When low equals its discovery number
- When it is node 0
- When it has no children
- What happens to the stack when a head is found?
- Nothing, the stack only grows
- It is cleared completely
- Nodes are popped until the head is popped
- How many DFS passes does Tarjan need compared with Kosaraju?
- One per node
- One, versus two for Kosaraju
- Two, the same as Kosaraju