Given n nodes labeled 0 to n − 1 and a list of undirected edges, return the number of connected components.
Start with n components. Each edge that joins two different sets merges them, so subtract one.
1function countComponents(n: number, edges: number[][]): number {2const parent = Array.from({ length: n }, (_, i) => i);3const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));4let count = n;5for (const [a, b] of edges) {6const ra = find(a), rb = find(b);7if (ra !== rb) { parent[ra] = rb; count--; }8}9return count;10}
6 singleton sets.
Space: play/pause · ←/→: step