← All Exercises
Union-Find with Path Compression
intermediatego
Background
Union-find answers connectivity queries in nearly constant amortized time; it powers Kruskal's algorithm, network clustering, and account deduplication.
Problem
Implement UnionFind with NewUnionFind(n), Find(x), Union(a, b), and Components(). Use path compression and union by rank, count components after applying every undirected edge, and reject invalid node indices.
Input
Node count n and a list of undirected edge pairs.
Output
The number of connected components after all unions, or an error for invalid input.
Sample tests
Sample 1
Input: n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Expected: 2
Sample 2
Input: n = 4, edges = [[0, 1], [2, 3], [1, 2]]
Expected: 1
Sample 3
Input: n = 3, edges = []
Expected: 3
Your solution
Learning objective
Implement disjoint sets with path compression and union by rank, and count connected components.