class UnionFind { constructor(n) { this.parent = Array.from({ length: n }, (_, i) => i); } find(x) { if (this.parent[x] !== x) { this.parent[x] = this.find(this.parent[x]); } return this.parent[x]; } union(a, b) { const rootA = this.find(a); const rootB = this.find(b); if (rootA !== rootB) { this.parent[rootB] = rootA; } } } const uf = new UnionFind(5); uf.union(0, 1); uf.union(1, 2); uf.union(3, 4); console.log(uf.parent);
After union(0,1), parent of 1 becomes 0. After union(1,2), parent of 2 becomes 0 (since 1's root is 0). After union(3,4), parent of 4 becomes 3. So the parent array is [0,0,0,3,3].
The 'find' function returns the root parent of the element, which uniquely identifies the set it belongs to.
Setting parent of rootA to rootB without ensuring no cycles can cause a cycle if rootB is already a child of rootA, leading to infinite recursion in find.
Groups are: {0,1}, {2,3}, {4,5,6}, so total 3 connected components.
After unions, sets are {0,1,2} with root 0 and {3,4,5} with root 3. find(5) returns 3's root which is 3, and path compression sets parent of 5 to 3. The parent array is [0, 0, 0, 3, 3, 3].
