int[] parent = {0, 1, 2, 3, 4}; int[] rank = {0, 0, 0, 0, 0}; // union(0, 1) // union(1, 2) // union(3, 4) // After these unions, print the parent array.
Initially, each element is its own parent.
union(0,1) makes 0 the parent of 1.
union(1,2) finds root of 1 is 0, so union(0,2) makes 0 the parent of 2.
union(3,4) makes 3 the parent of 4.
Final parent array: [0,0,0,3,3]
find(2) checks parent[2] = 0, which is root since parent[0] = 0.
So, find(2) returns 0.
void union(int x, int y) { int rootX = find(x); int rootY = find(y); if (rootX == rootY) return; if (rank[rootX] > rank[rootY]) { parent[rootY] = rootX; } else if (rank[rootX] < rank[rootY]) { parent[rootX] = rootY; } else { parent[rootX] = rootY; } }
When ranks are equal, the code attaches rootX under rootY but does not increase rank[rootY].
This causes rank to be incorrect and may degrade performance.
Option D uses correct Java syntax with braces and parentheses.
Option D misses parentheses in if condition causing syntax error.
Option D misses braces but is valid Java syntax (single statement if), but path compression requires braces to assign parent[x].
Option D returns without path compression update.
Unions form groups: {0,1,2}, {3,4}, {5,6}.
Remaining single elements: { } (none).
Total connected components = 3.
