TExcelTAD
Home › Graph Algorithms › Tarjan's Algorithm with Low-Links

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 Θ(V+E)\Theta(V + E) 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: u.index=0,1,2,…u.\textit{index} = 0, 1, 2, \ldots 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 uu is

u.low=min⁡({u.index}∪{w.index:w on the stack, reached from u’s subtree by one non-tree edge})u.\textit{low} = \min \bigl( \{ u.\textit{index} \} \cup \{ w.\textit{index} : w \text{ on the stack, reached from } u\text{'s subtree by one non-tree edge} \} \bigr)

computed bottom-up as the search returns. The key fact: uu is the root of its component exactly when u.low=u.indexu.\textit{low} = u.\textit{index}, that is, nothing in uu's subtree can climb back above uu to a vertex whose component is still open. At that moment the component of uu is precisely uu and everything above it on the stack.

text
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 component

Edges to vertices that are not on the stack (line 7 fails) lead into components that were already output; they cannot help uu 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.

python · try it yourself
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 {F,G,H}\{F, G, H\}: when the search returns to FF, nothing below it reaches above it, so FF is a root. DD's edge to EE is a back edge to a vertex still on the stack, so D.low=E.index=3D.\textit{low} = E.\textit{index} = 3 and DD is not a root; EE is, and pops {D,E}\{D, E\}. The edge B→DB \to D is examined after {D,E}\{D, E\} has been output: DD is off the stack and the edge is ignored. Finally CC's back edge to AA propagates low=0\textit{low} = 0 up through BB, and AA 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 rr is the root of its component, no vertex of rr's subtree has an edge to a stacked vertex discovered before rr: such a vertex xx is still open, so it lies on the current DFS path or can reach a vertex on it, which is an ancestor of rr; then rr's subtree could reach an ancestor of rr, which can reach rr (by the tree path), making that ancestor part of rr's component and contradicting that rr is the first-discovered vertex of it.

A non-root has low < index. If uu is not the root, its component's root rr is a proper ancestor, and there is a path from uu back to rr. The first edge of that path to leave uu's subtree goes to a vertex discovered before uu that is still on the stack (it is in the same component as uu, which is still open), so line 6 or 8 lowers u.lowu.\textit{low} below u.indexu.\textit{index}.

What gets popped is exactly the component. When root rr pops, the stack above rr holds vertices of rr's subtree that were not popped earlier, i.e. not in components rooted deeper. They are all in rr's component: each could reach back above itself, and the chain of such climbs ends at rr.

Each vertex is pushed and popped once, and each edge is examined once, so the running time is Θ(V+E)\Theta(V + E). 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.

python · try it yourself
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 −1-1 for "undiscovered".

cpp · try it yourself
#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?

  1. When a back edge is found
  2. When the search returns from a vertex uu with u.low=u.indexu.\textit{low} = u.\textit{index}
  3. After the second DFS
  4. When the stack is empty

Why are edges to vertices that are no longer on the stack ignored?

  1. They are tree edges
  2. They lead into components that were already output, so they cannot connect uu back to an open vertex
  3. They are self-loops
  4. They would make the algorithm quadratic

In which order does Tarjan's algorithm output the components?

  1. Topological order of the component graph
  2. Reverse topological order: a component after all components reachable from it
  3. Alphabetical order
  4. Decreasing size