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:
find — flatten the tree on the way up.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 nodeWhy 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 ≤ 20000..n-1.Sample tests