QuestionsDSA

Number of Connected Components

Union-Find (Disjoint Set)MediumDSA

Given n nodes labelled 0..n-1 and a list of undirected edges, count how many connected components the graph has. e.g. n=5, edges=[[0,1],[1,2],[3,4]] → 2.

What it tests

Reaching for Union-Find (Disjoint Set Union) when the question is purely about connectivity/grouping rather than paths.

Approach & answer

Start with n components. Each edge unions two nodes; a union that actually merges two different sets drops the count by one. Union-Find keeps a `parent` array where `find(x)` walks to the set representative and `union(a,b)` links one root under the other. Two optimisations make it near-O(1) amortised per op: path compression (point nodes directly at the root during find) and union by rank/size (attach the smaller tree under the larger). The signal for DSU: the problem is about 'are these in the same group / how many groups', edges arrive incrementally, or you need cycle detection in an undirected graph — cheaper and simpler than BFS/DFS flood-fill when you only care about membership, not traversal order or shortest path. Same tool powers accounts-merge, redundant-connection, and Kruskal's MST.

Use this technique when

Connectivity / grouping / 'same set?' / undirected cycle detection, edges added incrementally → Union-Find.

Complexity

Time ~O((n+e)·α(n)) ≈ near-linear · Space O(n)

References

js