Algo-Sim › Advanced Graphs
Strongly Connected Components
Hard · Advanced Graphs · step through it in Java, Python and C++ on your own input
Group a directed graph into strongly connected components: Kosaraju’s two DFS passes (finish order, then the reversed graph) or Tarjan’s one pass with low-links.
Problem
Given a directed graph on nodes 0 … n − 1, split the nodes into strongly connected components: maximal groups in which every node can reach every other along the edges. Return the components, each as a list of nodes.
Constraints
- 1 ≤ n ≤ 10⁵
- 0 ≤ edges.length ≤ 10⁵
- Directed edges; self-loops and cycles allowed
- O(V + E) with Kosaraju or Tarjan
Edge cases to test
- A DAG: every node is its own component
- One big cycle
- Self-loops
Follow-up questions
- Kosaraju or Tarjan?
- Both are O(V + E). Tarjan uses one DFS with low-links and a stack; Kosaraju needs the reversed graph and two passes but is easier to reason about.
- What is the condensation used for?
- Contracting each component gives a DAG, which enables DP on DAGs and 2-SAT.
Solution
Java
public List<List<Integer>> stronglyConnectedComponents(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>(), radj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
radj.add(new ArrayList<>());
}
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
radj.get(e[1]).add(e[0]);
}
boolean[] seen = new boolean[n];
Deque<Integer> order = new ArrayDeque<>();
for (int u = 0; u < n; u++) {
if (!seen[u]) finish(u, adj, seen, order);
}
Arrays.fill(seen, false);
List<List<Integer>> sccs = new ArrayList<>();
while (!order.isEmpty()) {
int u = order.pop();
if (seen[u]) continue;
List<Integer> comp = new ArrayList<>();
collect(u, radj, seen, comp);
sccs.add(comp);
}
return sccs;
}
private void finish(int u, List<List<Integer>> adj, boolean[] seen, Deque<Integer> order) {
seen[u] = true;
for (int v : adj.get(u)) {
if (!seen[v]) finish(v, adj, seen, order);
}
order.push(u);
}
private void collect(int u, List<List<Integer>> radj, boolean[] seen, List<Integer> comp) {
seen[u] = true;
comp.add(u);
for (int v : radj.get(u)) {
if (!seen[v]) collect(v, radj, seen, comp);
}
}Python
def strongly_connected_components(n, edges):
adj = [[] for _ in range(n)]
radj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
radj[v].append(u)
seen = [False] * n
order = []
def finish(u):
seen[u] = True
for v in adj[u]:
if not seen[v]:
finish(v)
order.append(u)
for u in range(n):
if not seen[u]:
finish(u)
def collect(u, comp):
seen[u] = True
comp.append(u)
for v in radj[u]:
if not seen[v]:
collect(v, comp)
seen = [False] * n
sccs = []
for u in reversed(order):
if seen[u]:
continue
comp = []
collect(u, comp)
sccs.append(comp)
return sccsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> stronglyConnectedComponents(int n, vector<vector<int>> &edges) {
vector<vector<int>> adj = {}, radj = {};
for (int i = 0; i < n; i++) {
adj.push_back({});
radj.push_back({});
}
for (vector<int> &e : edges) {
adj[e[0]].push_back(e[1]);
radj[e[1]].push_back(e[0]);
}
vector<bool> seen = vector<bool>(n);
deque<int> order = {};
for (int u = 0; u < n; u++) {
if (!seen[u])
finish(u, adj, seen, order);
}
fill(seen.begin(), seen.end(), false);
vector<vector<int>> sccs = {};
while (!order.empty()) {
int u = order.back();
order.pop_back();
if (seen[u])
continue;
vector<int> comp = {};
collect(u, radj, seen, comp);
sccs.push_back(comp);
}
return sccs;
}
void finish(int u, vector<vector<int>> &adj, vector<bool> &seen, deque<int> &order) {
seen[u] = true;
for (int v : adj[u]) {
if (!seen[v])
finish(v, adj, seen, order);
}
order.push_back(u);
}
void collect(int u, vector<vector<int>> &radj, vector<bool> &seen, vector<int> &comp) {
seen[u] = true;
comp.push_back(u);
for (int v : radj[u]) {
if (!seen[v])
collect(v, radj, seen, comp);
}
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)