Overview
Given n nodes labeled from 0 to n - 1 and a list of undirected edges, return the number of connected components in the graph.
Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length === 20 <= edges[i][0], edges[i][1] < n- No duplicate edges.
Examples
countComponents(5, [[0,1], [1,2], [3,4]]);
// => 2
// Component 1: {0, 1, 2}
// Component 2: {3, 4}countComponents(5, [[0,1], [1,2], [2,3], [3,4]]); // => 1 (all connected) countComponents(4, []); // => 4 (each node is its own component)
Solution
Reveal solution
function countComponents(n, edges) {
const parent = Array.from({ length: n }, (_, i) => i);
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // path compression
x = parent[x];
}
return x;
}
function union(a, b) {
const rootA = find(a), rootB = find(b);
if (rootA === rootB) return false;
parent[rootA] = rootB;
return true;
}
let components = n;
for (const [a, b] of edges) {
if (union(a, b)) components--;
}
return components;
}Union-Find with path compression. Start with n components and merge on each edge.
Resources
graph-connected-components.js
Graph Count Connected Components
mediumcodingAlgorithmsGraphs
Overview
Given n nodes labeled from 0 to n - 1 and a list of undirected edges, return the number of connected components in the graph.
Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length === 20 <= edges[i][0], edges[i][1] < n- No duplicate edges.
Examples
countComponents(5, [[0,1], [1,2], [3,4]]);
// => 2
// Component 1: {0, 1, 2}
// Component 2: {3, 4}countComponents(5, [[0,1], [1,2], [2,3], [3,4]]); // => 1 (all connected) countComponents(4, []); // => 4 (each node is its own component)
Solution
Reveal solution
function countComponents(n, edges) {
const parent = Array.from({ length: n }, (_, i) => i);
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // path compression
x = parent[x];
}
return x;
}
function union(a, b) {
const rootA = find(a), rootB = find(b);
if (rootA === rootB) return false;
parent[rootA] = rootB;
return true;
}
let components = n;
for (const [a, b] of edges) {
if (union(a, b)) components--;
}
return components;
}Union-Find with path compression. Start with n components and merge on each edge.
Resources
NameTopicDifficulty
103 of 103 problems