Strongly Connected Components
A strongly connected component is a largest group of vertices in a directed graph where every vertex can reach every other. Kosaraju's and Tarjan's algorithms both find all of them in O(V + E).
Mutual Reachability
In a directed graph, vertex u is strongly connected to v when there is a path from u to v and a path from v to u. A strongly connected component (SCC) is a maximal set of vertices in which every pair is strongly connected in this way. Maximal means no vertex can be added without breaking the rule.
Every vertex belongs to exactly one SCC. A vertex on no cycle forms an SCC by itself. In the graph above, 2 → 3 → 4 → 2 is a cycle, so {2, 3, 4} is one component; 0 and 1 point at each other; 6 and 7 point at each other; 5 stands alone. That gives 4 SCCs for 8 vertices.
- Defined only for directed graphs; in an undirected graph the analogue is a plain connected component
- A graph is strongly connected when it has exactly one SCC
- Mutual reachability is an equivalence relation (reflexive, symmetric, transitive), which is why the components never overlap
The Condensation Graph Is a DAG
Replace every SCC with a single node, and draw an edge from component A to component B whenever some edge of the original graph goes from a vertex in A to a vertex in B. The result is the condensation graph, also called the component graph.
The condensation is always a directed acyclic graph. If it had a cycle A → B → A, every vertex of A could reach every vertex of B and back, so A and B would be one component, not two. In the example the condensation is the chain {6, 7} → {5} → {2, 3, 4} → {0, 1}.
A component with no incoming edges in the condensation is a source component; one with no outgoing edges is a sink component. Both algorithms below exploit this structure.
- A vertex with a self-loop is still its own SCC; the loop adds no edge to the condensation
- Parallel edges between two components collapse into one condensation edge, so the condensation can have far fewer edges than the original graph
Kosaraju's Algorithm
- Pass 1 – run DFS over the original graph from every unvisited vertex. Push each vertex onto a stack when it finishes (after all its descendants).
- Transpose – build Gᵀ by reversing every edge.
- Pass 2 – pop vertices from the stack (latest finish first). For each vertex not yet assigned, run DFS on Gᵀ; every vertex that search reaches forms one SCC.
Kosaraju's algorithm (also credited to Sharir) finds every SCC with two depth-first searches and one reversal of the graph.
Why it works. In pass 1, the vertex that finishes last lies in a source component of the condensation: if a component C has an edge into component D, the latest finish time in C is later than every finish time in D. Reversing every edge keeps each component intact, because a cycle reversed is still a cycle, but it turns that source component into a sink. A DFS started inside a sink can never leave it, so pass 2 collects exactly one component. Removing it exposes the next source, and the reverse finish order visits the sources one after another.
Running pass 2 on the original graph instead is the classic mistake. In the example a DFS from 6 follows 7 → 5 → 2 → 3 → 0 and swallows all 8 vertices. The Kosaraju's algorithm lesson walks through both passes on another graph and gives an iterative version.
- Components come out in topological order of the condensation
- Needs the graph twice: the original and its transpose
- Only finish order matters in pass 1, not discovery order
Terms, operations, and practical uses
Core vocabulary
- Strongly connectedu reaches v and v reaches u.
- SCCA maximal set of mutually reachable vertices.
- CondensationThe DAG made by shrinking each SCC to one node.
- Transpose graphThe same vertices with every edge reversed; it has the same SCCs.
- Low-linkSmallest discovery time reachable from a vertex's DFS subtree through vertices still on the stack.
Mechanisms
- Kosaraju pass 1DFS on G; push each vertex when it finishes.
- Kosaraju pass 2Pop in reverse finish order; each DFS on Gᵀ is one SCC.
- Tarjan root testlow[u] == disc[u]: pop the stack down to u.
- ComplexityO(V + E) time, O(V) extra space (plus Gᵀ for Kosaraju).
Related lessons
- Depth-First SearchFinish times and edge types drive both SCC algorithms.
- Topological SortThe condensation is a DAG, so it can be ordered.
- Cycle DetectionA non-trivial SCC is exactly a set of vertices sharing cycles.
- GraphsDirected graphs, adjacency lists and reachability.
- DeadlocksCycles in a wait-for graph are the OS view of the same idea.
Code in Python, C++ and Java
import sys
sys.setrecursionlimit(10_000)
N = 8
EDGES = [(0, 1), (1, 0), (2, 3), (3, 0), (3, 4), (4, 2), (5, 2), (6, 7), (7, 5), (7, 6)]
def build(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
return adj
def transpose(adj):
radj = [[] for _ in adj]
for u, targets in enumerate(adj):
for v in targets:
radj[v].append(u)
return radj
def kosaraju(adj):
n = len(adj)
seen = [False] * n
order = []
def dfs1(u):
seen[u] = True
for v in adj[u]:
if not seen[v]:
dfs1(v)
order.append(u) # u finishes only after everything it can reach
for u in range(n):
if not seen[u]:
dfs1(u)
radj = transpose(adj)
comp = [-1] * n
sccs = []
def dfs2(u, c):
comp[u] = c
sccs[c].append(u)
for v in radj[u]:
if comp[v] == -1:
dfs2(v, c)
# Latest finisher first: it lies in a source component of the original graph,
# so in the transpose nothing outside its own component is reachable.
for u in reversed(order):
if comp[u] == -1:
sccs.append([])
dfs2(u, len(sccs) - 1)
return order, [sorted(s) for s in sccs], comp
def tarjan(adj):
n = len(adj)
disc = [-1] * n
low = [0] * n
on_stack = [False] * n
stack = []
sccs = []
timer = 0
def dfs(u):
nonlocal timer
disc[u] = low[u] = timer
timer += 1
stack.append(u)
on_stack[u] = True
for v in adj[u]:
if disc[v] == -1:
dfs(v)
low[u] = min(low[u], low[v])
elif on_stack[v]:
low[u] = min(low[u], disc[v])
if low[u] == disc[u]:
# u is the root of its component: pop everything above it.
scc = []
while True:
v = stack.pop()
on_stack[v] = False
scc.append(v)
if v == u:
break
sccs.append(sorted(scc))
for u in range(n):
if disc[u] == -1:
dfs(u)
return sccs, disc, low
def reach(adj, start):
seen = {start}
todo = [start]
while todo:
u = todo.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
todo.append(v)
return sorted(seen)
def show(vertices):
return "{" + ", ".join(str(v) for v in vertices) + "}"
adj = build(N, EDGES)
print(f"Graph: {N} vertices, {len(EDGES)} edges")
order, sccs, comp = kosaraju(adj)
print("Pass 1 finish order:", " ".join(str(v) for v in order))
print("Pass 2 start order: ", " ".join(str(v) for v in reversed(order)))
print("Wrong: DFS from 6 on the original graph reaches", show(reach(adj, 6)))
for i, scc in enumerate(sccs):
print(f"Kosaraju SCC {i + 1}: {show(scc)}")
dag = sorted({(comp[u], comp[v]) for u, v in EDGES if comp[u] != comp[v]})
print("Condensation DAG:", ", ".join(f"C{a + 1} -> C{b + 1}" for a, b in dag))
t_sccs, disc, low = tarjan(adj)
print()
print("Tarjan v disc low")
for v in range(N):
print(f"{v:>9} {disc[v]:>4} {low[v]:>3}")
print("Tarjan SCCs (reverse topological):", " ".join(show(s) for s in t_sccs))
same = sorted(sccs) == sorted(t_sccs)
print("Both algorithms agree:", "yes" if same else "no")#include <algorithm>
#include <cstdio>
#include <functional>
#include <set>
#include <string>
#include <utility>
#include <vector>
using Graph = std::vector<std::vector<int>>;
const int N = 8;
const std::vector<std::pair<int, int>> EDGES = {{0, 1}, {1, 0}, {2, 3}, {3, 0}, {3, 4},
{4, 2}, {5, 2}, {6, 7}, {7, 5}, {7, 6}};
Graph build(int n, const std::vector<std::pair<int, int>>& edges) {
Graph adj(n);
for (auto [u, v] : edges) adj[u].push_back(v);
return adj;
}
Graph transpose(const Graph& adj) {
Graph radj(adj.size());
for (int u = 0; u < (int)adj.size(); u++)
for (int v : adj[u]) radj[v].push_back(u);
return radj;
}
struct Kosaraju {
std::vector<int> order, comp;
std::vector<std::vector<int>> sccs;
};
Kosaraju kosaraju(const Graph& adj) {
int n = adj.size();
Kosaraju k;
std::vector<bool> seen(n, false);
std::function<void(int)> dfs1 = [&](int u) {
seen[u] = true;
for (int v : adj[u])
if (!seen[v]) dfs1(v);
k.order.push_back(u); // u finishes only after everything it can reach
};
for (int u = 0; u < n; u++)
if (!seen[u]) dfs1(u);
Graph radj = transpose(adj);
k.comp.assign(n, -1);
std::function<void(int, int)> dfs2 = [&](int u, int c) {
k.comp[u] = c;
k.sccs[c].push_back(u);
for (int v : radj[u])
if (k.comp[v] == -1) dfs2(v, c);
};
// Latest finisher first: it lies in a source component of the original graph,
// so in the transpose nothing outside its own component is reachable.
for (int i = n - 1; i >= 0; i--) {
int u = k.order[i];
if (k.comp[u] == -1) {
k.sccs.push_back({});
dfs2(u, k.sccs.size() - 1);
}
}
for (auto& s : k.sccs) std::sort(s.begin(), s.end());
return k;
}
struct Tarjan {
std::vector<std::vector<int>> sccs;
std::vector<int> disc, low;
};
Tarjan tarjan(const Graph& adj) {
int n = adj.size(), timer = 0;
Tarjan t;
t.disc.assign(n, -1);
t.low.assign(n, 0);
std::vector<bool> onStack(n, false);
std::vector<int> stack;
std::function<void(int)> dfs = [&](int u) {
t.disc[u] = t.low[u] = timer++;
stack.push_back(u);
onStack[u] = true;
for (int v : adj[u]) {
if (t.disc[v] == -1) {
dfs(v);
t.low[u] = std::min(t.low[u], t.low[v]);
} else if (onStack[v]) {
t.low[u] = std::min(t.low[u], t.disc[v]);
}
}
if (t.low[u] == t.disc[u]) {
// u is the root of its component: pop everything above it.
std::vector<int> scc;
int v;
do {
v = stack.back();
stack.pop_back();
onStack[v] = false;
scc.push_back(v);
} while (v != u);
std::sort(scc.begin(), scc.end());
t.sccs.push_back(scc);
}
};
for (int u = 0; u < n; u++)
if (t.disc[u] == -1) dfs(u);
return t;
}
std::vector<int> reach(const Graph& adj, int start) {
std::set<int> seen = {start};
std::vector<int> todo = {start};
while (!todo.empty()) {
int u = todo.back();
todo.pop_back();
for (int v : adj[u])
if (seen.insert(v).second) todo.push_back(v);
}
return {seen.begin(), seen.end()};
}
std::string show(const std::vector<int>& vs) {
std::string s = "{";
for (size_t i = 0; i < vs.size(); i++) s += (i ? ", " : "") + std::to_string(vs[i]);
return s + "}";
}
std::string join(const std::vector<int>& vs) {
std::string s;
for (size_t i = 0; i < vs.size(); i++) s += (i ? " " : "") + std::to_string(vs[i]);
return s;
}
int main() {
Graph adj = build(N, EDGES);
std::printf("Graph: %d vertices, %d edges\n", N, (int)EDGES.size());
Kosaraju k = kosaraju(adj);
std::vector<int> rev(k.order.rbegin(), k.order.rend());
std::printf("Pass 1 finish order: %s\n", join(k.order).c_str());
std::printf("Pass 2 start order: %s\n", join(rev).c_str());
std::printf("Wrong: DFS from 6 on the original graph reaches %s\n", show(reach(adj, 6)).c_str());
for (size_t i = 0; i < k.sccs.size(); i++)
std::printf("Kosaraju SCC %zu: %s\n", i + 1, show(k.sccs[i]).c_str());
std::set<std::pair<int, int>> dag;
for (auto [u, v] : EDGES)
if (k.comp[u] != k.comp[v]) dag.insert({k.comp[u], k.comp[v]});
std::string line;
for (auto [a, b] : dag)
line += (line.empty() ? "" : ", ") + ("C" + std::to_string(a + 1)) + " -> C" +
std::to_string(b + 1);
std::printf("Condensation DAG: %s\n", line.c_str());
Tarjan t = tarjan(adj);
std::printf("\nTarjan v disc low\n");
for (int v = 0; v < N; v++) std::printf("%9d %4d %3d\n", v, t.disc[v], t.low[v]);
std::string found;
for (size_t i = 0; i < t.sccs.size(); i++) found += (i ? " " : "") + show(t.sccs[i]);
std::printf("Tarjan SCCs (reverse topological): %s\n", found.c_str());
auto a = k.sccs, b = t.sccs;
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
std::printf("Both algorithms agree: %s\n", a == b ? "yes" : "no");
}import java.util.*;
import java.util.stream.*;
public class Main {
static final int N = 8;
static final int[][] EDGES = {
{0, 1}, {1, 0}, {2, 3}, {3, 0}, {3, 4}, {4, 2}, {5, 2}, {6, 7}, {7, 5}, {7, 6}
};
static List<List<Integer>> build(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) adj.get(e[0]).add(e[1]);
return adj;
}
static List<List<Integer>> transpose(List<List<Integer>> adj) {
List<List<Integer>> radj = new ArrayList<>();
for (int i = 0; i < adj.size(); i++) radj.add(new ArrayList<>());
for (int u = 0; u < adj.size(); u++)
for (int v : adj.get(u)) radj.get(v).add(u);
return radj;
}
// ---- Kosaraju ----
static List<List<Integer>> adj, radj;
static boolean[] seen;
static List<Integer> order = new ArrayList<>();
static int[] comp;
static List<List<Integer>> sccs = new ArrayList<>();
static void dfs1(int u) {
seen[u] = true;
for (int v : adj.get(u))
if (!seen[v]) dfs1(v);
order.add(u); // u finishes only after everything it can reach
}
static void dfs2(int u, int c) {
comp[u] = c;
sccs.get(c).add(u);
for (int v : radj.get(u))
if (comp[v] == -1) dfs2(v, c);
}
static void kosaraju() {
int n = adj.size();
seen = new boolean[n];
for (int u = 0; u < n; u++)
if (!seen[u]) dfs1(u);
radj = transpose(adj);
comp = new int[n];
Arrays.fill(comp, -1);
// Latest finisher first: it lies in a source component of the original graph,
// so in the transpose nothing outside its own component is reachable.
for (int i = n - 1; i >= 0; i--) {
int u = order.get(i);
if (comp[u] == -1) {
sccs.add(new ArrayList<>());
dfs2(u, sccs.size() - 1);
}
}
for (List<Integer> s : sccs) Collections.sort(s);
}
// ---- Tarjan ----
static int[] disc, low;
static boolean[] onStack;
static Deque<Integer> stack = new ArrayDeque<>();
static List<List<Integer>> tSccs = new ArrayList<>();
static int timer = 0;
static void tdfs(int u) {
disc[u] = low[u] = timer++;
stack.push(u);
onStack[u] = true;
for (int v : adj.get(u)) {
if (disc[v] == -1) {
tdfs(v);
low[u] = Math.min(low[u], low[v]);
} else if (onStack[v]) {
low[u] = Math.min(low[u], disc[v]);
}
}
if (low[u] == disc[u]) {
// u is the root of its component: pop everything above it.
List<Integer> scc = new ArrayList<>();
int v;
do {
v = stack.pop();
onStack[v] = false;
scc.add(v);
} while (v != u);
Collections.sort(scc);
tSccs.add(scc);
}
}
static void tarjan() {
int n = adj.size();
disc = new int[n];
low = new int[n];
onStack = new boolean[n];
Arrays.fill(disc, -1);
for (int u = 0; u < n; u++)
if (disc[u] == -1) tdfs(u);
}
static List<Integer> reach(int start) {
TreeSet<Integer> seenSet = new TreeSet<>(List.of(start));
Deque<Integer> todo = new ArrayDeque<>(List.of(start));
while (!todo.isEmpty()) {
int u = todo.pop();
for (int v : adj.get(u))
if (seenSet.add(v)) todo.push(v);
}
return new ArrayList<>(seenSet);
}
static String show(List<Integer> vs) {
return vs.stream().map(String::valueOf).collect(Collectors.joining(", ", "{", "}"));
}
static String join(List<Integer> vs) {
return vs.stream().map(String::valueOf).collect(Collectors.joining(" "));
}
public static void main(String[] args) {
adj = build(N, EDGES);
System.out.printf("Graph: %d vertices, %d edges%n", N, EDGES.length);
kosaraju();
List<Integer> rev = new ArrayList<>(order);
Collections.reverse(rev);
System.out.println("Pass 1 finish order: " + join(order));
System.out.println("Pass 2 start order: " + join(rev));
System.out.println("Wrong: DFS from 6 on the original graph reaches " + show(reach(6)));
for (int i = 0; i < sccs.size(); i++)
System.out.printf("Kosaraju SCC %d: %s%n", i + 1, show(sccs.get(i)));
TreeSet<List<Integer>> dag = new TreeSet<>(
Comparator.<List<Integer>>comparingInt(p -> p.get(0)).thenComparingInt(p -> p.get(1)));
for (int[] e : EDGES)
if (comp[e[0]] != comp[e[1]]) dag.add(List.of(comp[e[0]], comp[e[1]]));
String line = dag.stream()
.map(p -> "C" + (p.get(0) + 1) + " -> C" + (p.get(1) + 1))
.collect(Collectors.joining(", "));
System.out.println("Condensation DAG: " + line);
tarjan();
System.out.println();
System.out.println("Tarjan v disc low");
for (int v = 0; v < N; v++) System.out.printf("%9d %4d %3d%n", v, disc[v], low[v]);
String found = tSccs.stream().map(Main::show).collect(Collectors.joining(" "));
System.out.println("Tarjan SCCs (reverse topological): " + found);
Set<List<Integer>> a = new HashSet<>(sccs), b = new HashSet<>(tSccs);
System.out.println("Both algorithms agree: " + (a.equals(b) ? "yes" : "no"));
}
}Step through it
Running on 0→1, 1→0, 2→3, 3→0, 3→4, 4→2, 5→2, 6→7, 7→5, 7→6
Tarjan's Algorithm
- Visit u – set disc[u] = low[u] = timer++, push u, mark it on the stack.
- Tree edge u → v (v unvisited) – recurse into v, then low[u] = min(low[u], low[v]).
- Back edge u → v (v on the stack) – low[u] = min(low[u], disc[v]).
- Root test – after all edges, if low[u] == disc[u], pop the stack down to u and report that set as one SCC.
Tarjan's algorithm finds the SCCs in a single DFS and never builds the transpose. It gives each vertex a discovery time disc[u], the counter value when the DFS first reaches u, and a low-link value low[u], the smallest discovery time reachable from u's subtree using tree edges plus at most one edge back to a vertex still on the stack.
Visited vertices are pushed onto an explicit stack and stay there until their component is complete. When the DFS finishes u and finds low[u] == disc[u], nothing in u's subtree can reach anything older than u, so u is the root of an SCC. Pop the stack down to u: those vertices are the component.
The on-stack check matters. An edge to a vertex that is visited but already popped leads into a finished component, which cannot be part of the current one, so it must not lower low[u]. In the graph above, 3 → 0 is ignored for this reason. The Tarjan's algorithm lesson traces disc, low and the stack step by step, including what goes wrong without this check.
- Components come out in reverse topological order: sinks first
- In the graph above Tarjan finds four roots, so four components
- Recursion depth can reach V; use an explicit stack for very large graphs
Worked Example: Tarjan on Two Cycles
The tracer runs Kosaraju on the graph above. Here is Tarjan on a smaller graph with 5 vertices and the edges 0→1, 1→2, 2→0, 2→3, 3→4, 4→3: a triangle 0, 1, 2 with an edge out to a pair 3, 4 that point at each other.
The DFS starts at 0 and walks 0 → 1 → 2, giving disc = 0, 1, 2 and pushing all three. From 2, the edge to 0 hits a vertex still on the stack, so low[2] drops to 0. The edge 2 → 3 is new: 3 gets disc 3, then 4 gets disc 4. The edge 4 → 3 is a back edge to a stacked vertex, so low[4] = 3.
Now the DFS unwinds. At 3, low[3] = min(3, low[4]) = 3, which equals disc[3], so 3 is a root: pop 4 and 3, the first component {3, 4}. Back at 2, low[2] stays 0 because the finished low[3] = 3 is larger. 1 and then 0 inherit low = 0, and 0 has low == disc, so popping down to 0 gives {0, 1, 2}.
- The sink component {3, 4} is reported first, the source {0, 1, 2} last: reverse topological order
- Kosaraju on the same graph finds {0, 1, 2} first, because its pass 2 starts from a source component
- Practise the two-pass version on Strongly Connected Components (Kosaraju)
Time Complexity and Kosaraju vs Tarjan
Both algorithms run in O(V + E) time on an adjacency list. Kosaraju does two full DFS passes and one pass to build the transpose, each O(V + E). Tarjan does one DFS, and every vertex is pushed onto and popped from its stack exactly once. On an adjacency matrix both become O(V²).
Space is O(V) for the visited flags, stack and recursion, plus O(V + E) for Kosaraju's transposed copy of the graph.
| Aspect | Kosaraju | Tarjan |
|---|---|---|
| DFS passes | 2 | 1 |
| Needs the transpose | yes, O(V + E) extra | no |
| State per vertex | visited flag, finish order | disc, low, on-stack flag |
| Order of output | topological (sources first) | reverse topological (sinks first) |
| Time | O(V + E) | O(V + E) |
| Ease of getting right | simpler to reason about | subtle: low-link and on-stack rules |
| Constant factor | higher (two passes) | lower |
- Choose Kosaraju when clarity matters, Tarjan when memory or speed matters
- Path-based (Gabow's) algorithm is a third O(V + E) method using two stacks
- Brute force, a reachability search from every vertex, costs O(V · (V + E))
Where SCCs Are Used
SCCs are the standard first step whenever a directed graph might contain cycles but the rest of the solution needs a DAG: find the components, condense, then work on the condensation.
- 2-SAT: build the implication graph; the formula is unsatisfiable exactly when some x and ¬x share an SCC
- Dependency cycles: every SCC with more than one vertex is a group of modules or tasks that depend on each other in a circle
- Deadlock detection: a cycle in a wait-for graph shows up as an SCC with more than one process
- Compilers: mutually recursive functions form one SCC of the call graph and are analysed together
- Web and social graphs: the SCCs show groups where everyone can reach everyone, such as the giant core of the web
- Minimum edges to make a graph strongly connected: max(sources, sinks) of the condensation, when it has more than one node
- Condensation plus topological sort gives a valid order for DP over a cyclic graph
- Related: cycle detection only asks whether a cycle exists; SCCs say which vertices share one