Number of Connected Components in an Undirected Graph
Difficulty: Medium
You're given n nodes labeled 0 to n - 1 and a list of undirected edges. Return the number of connected components: groups where every node can reach every other node in its group, but none outside it.
Examples
Input: n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output: 2
Nodes 0, 1, 2 are all connected to each other; nodes 3, 4 form a separate connected pair.
Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
Output: 1
The edges form one continuous chain touching every node.
Input: n = 4, edges = []
Output: 4
With no edges at all, every node is its own isolated component.
Constraints
1 <= n <= 2000
0 <= edges.length <= n × (n - 1) / 2
There are no self-loops or duplicate edges.
Approach
A connected component is everything reachable from one node. So build an adjacency list and scan the nodes. Each unvisited node starts a new component: add 1 to the count and run DFS or BFS from it to mark the whole component visited.
Union-Find is cleaner and scales better. Start with every node in its own group and merge the endpoints of each edge. The number of distinct groups left is the answer, with no adjacency list or traversal needed.
Solutions
DFS Traversal
Build an adjacency list and scan every node. Each unvisited node is a new component: run DFS from it to mark the whole component visited.
function countComponents(n, edges) {
const graph = Array.from({ length: n }, () => []);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
}
const visited = new Array(n).fill(false);
let count = 0;
function dfs(node) {
visited[node] = true;
for (const neighbor of graph[node]) {
if (!visited[neighbor]) dfs(neighbor);
}
}
for (let node = 0; node < n; node++) {
if (!visited[node]) {
count++;
dfs(node);
}
}
return count;
}Time: O(V + E) · Space: O(V + E)
Optimal - Union-Find
Start with n groups, one per node, and union the endpoints of every edge. Each successful merge lowers the group count by one; the final count is the number of components.
function countComponents(n, edges) {
const parent = Array.from({ length: n }, (_, i) => i);
const rank = new Array(n).fill(0);
let components = n;
function find(x) {
if (parent[x] !== x) parent[x] = find(parent[x]);
return parent[x];
}
function union(a, b) {
const rootA = find(a);
const rootB = find(b);
if (rootA === rootB) return;
if (rank[rootA] < rank[rootB]) {
parent[rootA] = rootB;
} else if (rank[rootA] > rank[rootB]) {
parent[rootB] = rootA;
} else {
parent[rootB] = rootA;
rank[rootA]++;
}
components--; // merging two groups always reduces the total by one
}
for (const [a, b] of edges) {
union(a, b);
}
return components;
}Time: O((V + E) × α(V)) - nearly O(V + E) · Space: O(V)