guest@cp-base:~/home/graph$
templates/tarjan.cpp
compilable
$cat templates/tarjan

Tarjan's Algorithm

SCC decomposition, bridges, and articulation points in a single O(V+E) DFS pass.

[Graph]|
Jul 9, 2026
|explanatory_notes.md|
#tarjan#scc#bridges#articulation-points#graph
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2e5 + 5;
vector<int> adj[MAXN];
int idx[MAXN], low[MAXN], comp[MAXN], timer_val;
bool inStack[MAXN];
stack<int> stk;
vector<vector<int>> sccs;
vector<pair<int,int>> bridges;
set<int> artPoints;

void dfs(int u, int par) {
    idx[u] = low[u] = timer_val++;
    stk.push(u); inStack[u] = true;
    int children = 0;
    for (int v : adj[u]) {
        if (v == par) continue;
        if (idx[v] == -1) {
            children++;
            dfs(v, u);
            low[u] = min(low[u], low[v]);
            if (low[v] == idx[v])
                bridges.push_back({u, v});
            if (par != -1 && low[v] >= idx[u])
                artPoints.insert(u);
        } else if (inStack[v]) {
            low[u] = min(low[u], idx[v]);
        }
    }
    if (par == -1 && children > 1)
        artPoints.insert(u);
    if (low[u] == idx[u]) {
        sccs.push_back({});
        int v;
        do {
            v = stk.top(); stk.pop();
            inStack[v] = false;
            sccs.back().push_back(v);
            comp[v] = sccs.size() - 1;
        } while (v != u);
    }
}

void tarjan(int n) {
    memset(idx, -1, sizeof idx);
    timer_val = 0;
    for (int i = 0; i < n; i++)
        if (idx[i] == -1) dfs(i, -1);
}
50 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Tarjan's Algorithm

Finds SCCs, bridges, and articulation points in one DFS pass.

How It Works

  • Assign each node a discovery index and a low-link value (earliest reachable ancestor)

  • Push nodes onto a stack during DFS

  • Bridge: edge (u,v)(u, v) where low[v]=idx[v]\text{low}[v] = \text{idx}[v] — removing it disconnects the graph

  • Articulation point (non-root): low[v]idx[u]\text{low}[v] \ge \text{idx}[u]

  • Articulation point (root): DFS root with >1> 1 children in the DFS tree

  • SCC: when low[u]=idx[u]\text{low}[u] = \text{idx}[u], pop everything from stack down to uu — that's one component
  • When to Use

  • Finding all bridges in an undirected graph

  • Finding articulation points (cut vertices)

  • SCC decomposition in directed graphs

  • Building the condensation DAG
  • Complexity

  • Time — O(V+E)O(V + E)

  • Space — O(V+E)O(V + E)