MediumPro challengePythonJavaScriptTypeScript

Count Connected Components (Union-Find)

Data StructuresGraphUnion-FindAlgorithms

Given n nodes (labelled 0 to n - 1) and a list of undirected edges,
return the number of connected components in the graph.

Implement a Union-Find (Disjoint Set) with:

  • Path compression in find — flatten the tree on the way up.
  • Union by rank in union — attach the smaller tree under the larger one.

solve(n, edges) builds the structure and returns the component count.

Examples

solve(5, [[0,1],[1,2],[3,4]])   → 2   // {0,1,2} and {3,4}
solve(5, [[0,1],[1,2],[2,3],[3,4]]) → 1   // all connected
solve(4, [])                    → 4   // no edges — 4 isolated nodes
solve(1, [])                    → 1   // single node

Why Union-Find beats BFS here
Each union is nearly O(1) amortised (inverse Ackermann), so the total cost
is O(n + e) vs O(n + e) BFS — but Union-Find uses far less memory and handles
dynamic edge insertion without rebuilding adjacency lists.

Constraints

  • 1 ≤ n ≤ 2000
  • No self-loops, no duplicate edges.
  • Nodes are integers 0..n-1.

Sample tests

Test #1No edges — every node is its own component
Input: [4,[]]
Output: 4
Test #2Two groups: {0,1,2} and {3,4}
Input: [5,[[0,1],[1,2],[3,4]]]
Output: 2
Test #3Chain of 5 nodes — all connected
Input: [5,[[0,1],[1,2],[2,3],[3,4]]]
Output: 1