Number of Connected Components in an Undirected Graph
Difficulty: Medium · Pattern: Union-Find · LeetCode #323
Given n nodes (labeled 0..n−1) and a list of undirected edges, return the number of connected components.
Examples
text
n = 5, edges = [[0,1],[1,2],[3,4]] → 2
n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] → 1Hints
- Every node starts as its own component. An edge that joins two different components merges them.
Approach
Union-Find: count = n. For each edge, if find(a) != find(b), union them and decrement count.
With path compression (or path halving) plus union by size/rank, each operation costs amortized O(α(n)), where α is the inverse Ackermann function, effectively constant. DFS/BFS counting also works in O(V + E). Union-Find shines when edges arrive online (one at a time) and you need the count after each.
Complexity
Time: O(E · α(n)) with Union-Find, O(V + E) with DFS. Space: O(n).
Python solution
def countComponents(n, edges):
parent, size = list(range(n)), [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
count = n
for a, b in edges:
ra, rb = find(a), find(b)
if ra != rb:
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
count -= 1
return countJavaScript solution
function countComponents(n, edges) {
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) { adj[a].push(b); adj[b].push(a); }
const seen = new Array(n).fill(false);
let count = 0;
for (let s = 0; s < n; s++) {
if (seen[s]) continue;
count++;
const stack = [s]; seen[s] = true;
while (stack.length) for (const v of adj[stack.pop()]) if (!seen[v]) { seen[v] = true; stack.push(v); }
}
return count;
}