Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Strongly Connected Components: Tarjan & Kosaraju

Two linear-time algorithms, and why they work.

Tarjan's 1972 algorithm finds every strongly connected component of a directed graph in a single depth-first search, emitting each component the moment the search leaves it for good. Kosaraju's two-pass algorithm is easier to state, but why it works is subtler. Both rest on one lemma about when DFS finishes the vertices of different components.

What you’ll learn

  • State and prove the finishing-time lemma for strongly connected components, and derive from it the correctness of the Kosaraju–Sharir algorithm.
  • Define low-link values precisely and prove Tarjan's root test: a vertex is the first of its component exactly when its low-link equals its discovery index.
  • Implement both algorithms in O(n+m)O(n + m), explain why edges into finished components must be ignored, and know which topological order of the condensation each one produces.
  • Describe the path-based method, and the state of the art for strong connectivity in dynamic and parallel settings.

One lemma about finishing times

DerivationProof
  1. f(C)=f[x]>f[y]for every y∈C′f(C) = f[x] > f[y] \quad \text{for every } y \in C'

    Case d(C)<d(C′)d(C) < d(C'). Let xx be the first vertex of CC discovered. At time d[x]d[x], all of C∪C′C \cup C' is white, and all of it is reachable from xx: inside CC, then across the edge into C′C'. By the white-path theorem, every vertex of C∪C′C \cup C' becomes a descendant of xx and finishes before xx:

  2. f(C)>d(C)>f[y]=f(C′)f(C) > d(C) > f[y] = f(C')

    Case d(C′)<d(C)d(C') < d(C). Let yy be the first vertex of C′C' discovered. All of C′C' becomes descendants of yy, so f(C′)=f[y]f(C') = f[y]. No vertex of CC is reachable from C′C', since otherwise the two components would reach each other and be one. So CC is still white when yy finishes, and is discovered only later:

  3. f(C∗)=max⁡v∈Vf[v]  ⟹  no edge enters C∗f(C^{*}) = \max_{v \in V} f[v] \;\Longrightarrow\; \text{no edge enters } C^{*}

    Corollary. The vertex that finishes last lies in a source component of the condensation, one that no edge enters: an edge C→C∗C \to C^{*} into its component C∗C^{*} would give CC a later finishing time.

Check your understanding

After a complete DFS of GG, in which component of the condensation does the vertex with the largest finishing time lie?

  1. A source component: no edge enters it
  2. A sink component: no edge leaves it
  3. The component of the vertex where the DFS started
  4. The component with the most vertices
Show the answer

A. A source component: no edge enters it

If an edge entered the last finisher's component C∗C^{*} from a component CC, the lemma would give f(C)>f(C∗)f(C) > f(C^{*}), contradicting that C∗C^{*} holds the largest finishing time. This holds wherever the search starts, which is what makes Kosaraju's second pass work.

Kosaraju–Sharir: two passes

S. Rao Kosaraju found the algorithm in 1978 but did not publish it; Micha Sharir published it independently in 1981. Kosaraju's algorithm makes two passes:

  1. Run DFS on GG and list the vertices in order of finishing.
  2. Reverse every edge. The reversed graph GRG^{R} has exactly the same components.
  3. Scan the list from the last finisher backward. Whenever the scanned vertex is unassigned, search GRG^{R} from it; the unassigned vertices it reaches form one component.
DerivationProof by induction on the searches
  1. f(C)=f[r]=max⁡{ f(C′):C′ not yet found }f(C) = f[r] = \max\{\, f(C') : C' \text{ not yet found} \,\}

    Suppose the first kk searches each produced one whole component, and the next search starts at rr, the unassigned vertex with the largest finishing time. Its component CC is entirely unassigned, and it has the largest finishing time among the components not yet found:

  2. C⊆search(r)C \subseteq \text{search}(r)

    The search covers CC. CC is strongly connected in GRG^{R} as well, and all of it is unassigned, so the search from rr reaches all of it.

  3. C′→C in G  ⟹  f(C′)>f(C)  ⟹  C′ already foundC' \to C \text{ in } G \;\Longrightarrow\; f(C') > f(C) \;\Longrightarrow\; C' \text{ already found}

    It covers nothing else. An edge of GRG^{R} leaving CC toward a component C′C' is an edge C′→CC' \to C of GG. By the lemma f(C′)>f(C)f(C') > f(C), so by the choice of rr, C′C' was already found and its vertices are assigned:

  4. C1,C2,…,Ckwith every condensation edge Ci→Cj having i<jC_1, C_2, \dots, C_k \quad\text{with every condensation edge } C_i \to C_j \text{ having } i < j

    Topological order. The same step shows that every component with an edge into CC is found before CC. So the components come out sources first:

python
def kosaraju(n, adj):
    """Component id per vertex; ids follow a topological order of the condensation."""
    radj = [[] for _ in range(n)]
    for u in range(n):
        for v in adj[u]:
            radj[v].append(u)
    seen, order = [False] * n, []          # pass 1: finishing order on G
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            v = next((w for w in it if not seen[w]), None)
            if v is None:
                order.append(u)            # u finishes
                stack.pop()
            else:
                seen[v] = True
                stack.append((v, iter(adj[v])))
    comp, c = [-1] * n, 0                  # pass 2: reversed graph, latest finisher first
    for s in reversed(order):
        if comp[s] == -1:
            comp[s], stack = c, [s]
            while stack:
                u = stack.pop()
                for v in radj[u]:
                    if comp[v] == -1:
                        comp[v] = c
                        stack.append(v)
            c += 1
    return comp

Explicit stacks keep deep graphs safe: the first pass resumes each vertex's neighbor iterator where it stopped. O(n+m)O(n + m) time and memory, but the algorithm builds GRG^{R} and scans every edge twice. The second pass may use any search, BFS included, since it only needs to collect what is reachable.

Tarjan: one pass with low-links

Tarjan's algorithm (1972) needs neither the reversed graph nor a second pass. Number the vertices in discovery order, disc[v]=0,1,2,…\text{disc}[v] = 0, 1, 2, \dots, and push each vertex onto a stack SS when it is discovered. A vertex leaves SS only once its whole component has been identified, so SS always holds exactly the discovered vertices not yet assigned to a component. Each component is identified at its root, the first of its vertices that DFS discovers.

low[v]=min⁡({disc[v]} ∪ {low[c]:c a DFS child of v} ∪ {disc[w]:v→w a non-tree edge, w∈S})\text{low}[v] = \min\Big(\{\text{disc}[v]\} \,\cup\, \{\text{low}[c] : c \text{ a DFS child of } v\} \,\cup\, \{\text{disc}[w] : v \to w \text{ a non-tree edge},\ w \in S\}\Big)
The low-link of vv: the smallest discovery index of a vertex still on SS that vv's subtree reaches by tree edges followed by one more edge.
DerivationProof
  1. r⇝v⇝x→w⇝rr \rightsquigarrow v \rightsquigarrow x \to w \rightsquigarrow r

    A root has low[v]=disc[v]\text{low}[v] = \text{disc}[v]. Suppose an edge x→wx \to w from vv's subtree reaches a vertex w∈Sw \in S with disc[w]<disc[v]\text{disc}[w] < \text{disc}[v]. Since ww is unassigned, the root rr of its component has not returned, so rr is on the recursion stack, an ancestor of xx; and disc[r]≤disc[w]<disc[v]\text{disc}[r] \le \text{disc}[w] < \text{disc}[v] makes it a proper ancestor of vv. Then vv and rr lie on a common cycle, so vv is not the root of its component:

  2. low[v]≤low[x]≤disc[w]<disc[v]\text{low}[v] \le \text{low}[x] \le \text{disc}[w] < \text{disc}[v]

    A non-root has low[v]<disc[v]\text{low}[v] < \text{disc}[v]. The root rr of vv's component is a proper ancestor of vv, and some path leads from vv to rr. Let x→wx \to w be its first edge that leaves vv's subtree. If ww were white when scanned, it would become a descendant of xx; and a vertex discovered while vv is active is vv's descendant. So ww was discovered before vv. It lies in vv's unfinished component, hence on SS:

  3. {vertices above v on S}∪{v}=C(v)\{\text{vertices above } v \text{ on } S\} \cup \{v\} = C(v)

    Exactly the component is popped. When root vv returns, every vertex above it on SS was discovered during vv's call, so it is a descendant of vv. A descendant whose component root is a proper descendant of vv was popped when that root returned. So everything above vv is in vv's component, and conversely every vertex of the component is a descendant of vv (white-path theorem) that is still waiting on SS:

python
import sys

def tarjan(n, adj):
    """Component id per vertex; ids follow a REVERSE topological order (sinks first)."""
    sys.setrecursionlimit(10_000 + 2 * n)
    disc, low = [-1] * n, [0] * n
    on_stack, stack, comp = [False] * n, [], [-1] * n
    timer = count = 0
    def visit(u):
        nonlocal timer, count
        disc[u] = low[u] = timer
        timer += 1
        stack.append(u)
        on_stack[u] = True
        for v in adj[u]:
            if disc[v] == -1:                  # tree edge
                visit(v)
                low[u] = min(low[u], low[v])
            elif on_stack[v]:                  # edge into an unfinished component
                low[u] = min(low[u], disc[v])
        if low[u] == disc[u]:                  # u is the root of its component
            while True:
                v = stack.pop()
                on_stack[v] = False
                comp[v] = count
                if v == u:
                    break
            count += 1
    for u in range(n):
        if disc[u] == -1:
            visit(u)
    return comp

O(n+m)O(n + m): each vertex is pushed and popped once and each edge scanned once. Components are numbered as they are popped, sinks first, because a component is popped only after every component it can reach.

Trace it on the graph with edges A→BA \to B, B→CB \to C, C→AC \to A, B→DB \to D, C→IC \to I, D→ED \to E, E→FE \to F, F→DF \to D, E→GE \to G, G→HG \to H, H→GH \to G and I→HI \to H, starting at AA and scanning neighbors alphabetically:

VertexdisclowComponent (popped)
AA00{A,B,C}\{A, B, C\} (4th)
BB10{A,B,C}\{A, B, C\}
CC20{A,B,C}\{A, B, C\}
II33{I}\{I\} (2nd)
HH44{G,H}\{G, H\} (1st)
GG54{G,H}\{G, H\}
DD66{D,E,F}\{D, E, F\} (3rd)
EE76{D,E,F}\{D, E, F\}
FF86{D,E,F}\{D, E, F\}
The search runs A,B,C,I,H,GA, B, C, I, H, G, pops {G,H}\{G, H\} and {I}\{I\}, then returns to BB and explores D,E,FD, E, F. When EE scans E→GE \to G, GG has already been popped, so the edge is ignored.
Check your understanding

In this trace, suppose a buggy version drops the on-stack test and lowers low[E]\text{low}[E] to disc[G]=5\text{disc}[G] = 5 when it scans E→GE \to G. What happens?

  1. Nothing changes: the value 5 never decides a root test
  2. {G,H}\{G, H\} is split into two components
  3. low[D]\text{low}[D] drops to 5, below disc[D]=6\text{disc}[D] = 6, so DD is never recognized as a root and {D,E,F}\{D, E, F\} is merged into {A,B,C}\{A, B, C\}
  4. The algorithm never terminates
Show the answer

C. low[D]\text{low}[D] drops to 5, below disc[D]=6\text{disc}[D] = 6, so DD is never recognized as a root and {D,E,F}\{D, E, F\} is merged into {A,B,C}\{A, B, C\}

With the bug, low[E]=5\text{low}[E] = 5 and then low[D]=min⁡(6,5)=5≠disc[D]\text{low}[D] = \min(6, 5) = 5 \ne \text{disc}[D], so D,E,FD, E, F stay on the stack until AA returns and pops AA through FF as one "component". The output becomes {G,H},{I},{A,B,C,D,E,F}\{G, H\}, \{I\}, \{A, B, C, D, E, F\}. The on-stack test is what limits low-links to unfinished components.

Path-based search, and the frontier

A third family keeps no low-links. While DFS walks down a path, an edge back to an unassigned vertex ww proves that the whole stretch of the path from ww to the current vertex lies in one component, so those vertices can be merged into one tentative component. Two stacks suffice: SS holds the unassigned vertices in discovery order, and PP holds the first vertex of each tentative component along the current path. The idea goes back to Purdom (1970) and Munro (1971); Dijkstra (1976) gave the first linear-time version, and Cheriyan & Mehlhorn (1996) and Gabow (2000) the modern form.

text
PATH-BASED-SCC(G):                             # Gabow (2000)
    counter ← 0;  S ← empty stack;  P ← empty stack
    for each vertex v: pre[v] ← undefined
    for each vertex v with pre[v] undefined: VISIT(v)

VISIT(v):
    pre[v] ← counter;  counter ← counter + 1
    push v onto S;  push v onto P
    for each edge v → w:
        if pre[w] is undefined:
            VISIT(w)
        else if w is not yet assigned to a component:
            while pre[top(P)] > pre[w]: pop P   # merge the cycle through w
    if top(P) = v:                               # v is the first vertex of a component
        pop P
        pop S down to and including v; output those vertices as one component

Linear time, components emitted sinks first as in Tarjan's algorithm; the only number stored per vertex is its preorder index.

AlgorithmDFS passesExtra dataComponents emitted
Kosaraju–Sharir2, on GG and on GRG^{R}visited flags, finishing order, the reversed graphsources first
Tarjan1discovery index, low-link and on-stack flag per vertexsinks first
Path-based (Gabow)1preorder index per vertex, two stackssinks first
All three run in O(n+m)O(n + m) time. Pearce (2016) showed that Tarjan's algorithm can be run in about n(1+3w)n(1 + 3w) bits for word size ww, down from n(2+5w)n(2 + 5w).

Collapse, then solve a DAG. Many problems on general directed graphs become DAG problems on the condensation. To collect as much value as possible on a walk that may repeat vertices, give each component the total value of its vertices (a walk that enters a component can visit all of it and leave from any vertex), then find a heaviest path in the condensation by dynamic programming in topological order. Reachability reduces the same way, since all vertices of a component reach the same set. The next Optimal lesson, 2-SAT, decides Boolean formulas this way.

Key takeaways

  • If an edge leads from component CC to component C′C', then f(C)>f(C′)f(C) > f(C'); so the last vertex to finish lies in a source component.
  • Kosaraju–Sharir: DFS on GG for finishing times, then searches on GRG^{R} from the latest unassigned finisher; each search is one component, found in topological order, in O(n+m)O(n + m).
  • Tarjan: one DFS with a stack and low-links; vv starts a component exactly when low[v]=disc[v]\text{low}[v] = \text{disc}[v]; edges into already-popped components must be ignored; components come out sinks first.
  • The path-based method (Dijkstra 1976; Cheriyan & Mehlhorn 1996; Gabow 2000) replaces low-links with a stack of tentative component boundaries, also in linear time.
  • Strong connectivity under edge deletions has near-linear total update time (2019), while parallel algorithms remain limited by the cost of parallel reachability.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A dynamic program must process the components of a graph sources first, and you computed the components with Tarjan's algorithm. What order should the program use?

  1. The order in which Tarjan's algorithm popped the components
  2. The components sorted by their smallest discovery time
  3. The reverse of the order in which the components were popped
  4. The components sorted by size, largest first
Show the answer

C. The reverse of the order in which the components were popped

Tarjan's algorithm pops a component only after every component it can reach has been popped, so popping order is a reverse topological order: sinks first. Reversing it gives sources first, at no extra cost. (Kosaraju's algorithm produces sources first directly.)

Question 2

In Tarjan's algorithm, vertex vv's call is about to return and low[v]<disc[v]\text{low}[v] < \text{disc}[v]. What follows?

  1. vv is the first vertex of its component, which is popped now
  2. vv shares its component with a proper ancestor, so it stays on the stack
  3. vv's component consists of vv alone
  4. vv cannot reach any vertex discovered before it
Show the answer

B. vv shares its component with a proper ancestor, so it stays on the stack

low[v]<disc[v]\text{low}[v] < \text{disc}[v] means vv's subtree reaches an earlier-discovered vertex of an unfinished component, which (by the root test) lies in vv's own component. So vv is not its component's root; it stays on the stack until that root returns.

Question 3

A proposed shortcut for Kosaraju's algorithm: skip the reversed graph, and run the second pass on GG itself, starting from the vertex with the smallest finishing time. Does it find the components?

  1. Yes: the earliest finisher always lies in a sink component, so a search from it cannot leave its component
  2. Yes, provided the first DFS starts in a source component
  3. No: a search in GG started inside a sink component still escapes into other components
  4. No: the earliest finisher need not lie in a sink component
Show the answer

D. No: the earliest finisher need not lie in a sink component

The lemma orders the latest finishing time of each component, not the earliest. With edges A→BA \to B, B→AB \to A, A→CA \to C and a DFS from AA that visits BB first, BB finishes first, yet its component {A,B}\{A, B\} has an edge to {C}\{C\}, and a search from BB in GG collects all three vertices.

Question 4

Why do parallel algorithms for strongly connected components avoid depth-first search?

  1. DFS needs more than linear memory
  2. Computing the lexicographically first DFS order is P-complete, so no polylogarithmic-depth parallel algorithm for it is expected
  3. DFS gives wrong answers on graphs with cycles
  4. Tarjan's algorithm takes quadratic time on dense graphs
Show the answer

B. Computing the lexicographically first DFS order is P-complete, so no polylogarithmic-depth parallel algorithm for it is expected

Reif (1985) showed that the lexicographically first DFS order is P-complete, so it has no polylogarithmic-depth algorithm unless every polynomial-time problem does (NC = P). Parallel SCC algorithms are built on reachability searches instead.

Further reading

  • R. E. Tarjan, "Depth-first search and linear graph algorithms," SIAM Journal on Computing 1(2) (1972), 146–160.
  • M. Sharir, "A strong-connectivity algorithm and its applications in data flow analysis," Computers & Mathematics with Applications 7(1) (1981), 67–72.
  • H. N. Gabow, "Path-based depth-first search for strong and biconnected components," Information Processing Letters 74(3–4) (2000), 107–114.
  • A. Bernstein, M. Probst Gutenberg & C. Wulff-Nilsen, "Decremental strongly-connected components and single-source reachability in near-linear time," STOC (2019).
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §20.5.