int parent[6] = {0, 0, 1, 2, 3, 4}; int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } int main() { printf("%d\n", find(5)); printf("%d\n", parent[5]); return 0; }
The initial parent array is [0, 0, 1, 2, 3, 4]. The find(5) call recursively finds the root parent of 5:
- parent[5] = 4, so find(4) is called.
- parent[4] = 3, so find(3) is called.
- parent[3] = 2, so find(2) is called.
- parent[2] = 1, so find(1) is called.
- parent[1] = 0, so find(0) is called.
- parent[0] = 0, so root is 0.
Path compression sets parent of all nodes in the path directly to 0. So parent[5] becomes 0.
Output is 0 (root) and parent[5] after compression is 0.
Calling find(5) triggers recursive path compression, setting the parent of every node on the path 5→4→3→2→1→0 directly to the root 0. Thus, parent[1..5] all become 0 (parent[1] already was). Updated array: [0, 0, 0, 0, 0, 0].
int parent[4] = {0, 0, 1, 2}; int find(int x) { if (parent[x] == x) { return x; } return find(parent[x]); } int main() { printf("%d\n", find(3)); return 0; }
The find function correctly computes the root (0) for node 3 via recursion: 3→2→1→0, stopping since parent[0] == 0. However, it lacks path compression as there is no parent[x] = find(parent[x]) update. No errors occur: compiles fine, runs without segfault or stack overflow, outputs 0.
The implementation bug is missing path compression, but the question asks for errors caused by calling find(3), of which there are none.
int parent[5] = {0, 1, 2, 3, 4}; void union_set(int a, int b) { a = find(a); b = find(b); if (a != b) { parent[b] = a; } } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } int main() { union_set(0, 1); union_set(1, 2); union_set(3, 4); printf("%d\n", find(2)); printf("%d\n", parent[2]); printf("%d\n", find(4)); return 0; }
Unions:
- union_set(0,1): parent[1] = 0
- union_set(1,2): find(1) = 0, find(2) = 2, parent[2] = 0
- union_set(3,4): parent[4] = 3
Find(2): parent[2] = 0, so root is 0. Path compression sets parent[2] = 0.
parent[2] after find is 0.
Find(4): parent[4] = 3, root is 3.
Path compression flattens the tree, making future find operations faster. The amortized time per find becomes almost constant, bounded by the inverse Ackermann function, which grows extremely slowly.