Concept Flow - Path Compression in Union Find
Start: Find(x)
Is parent[x
Return x
Set parent[x
Return root
Find the root of x. If x is not root, recursively find root and update x's parent to root for faster future queries.
int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; }
| Step | Operation | Node x | parent[x] before | Recursive Call | parent[x] after | Visual State |
|---|---|---|---|---|---|---|
| 1 | Call find(4) | 4 | 3 | find(3) | ? | 4->3->2->2 |
| 2 | Call find(3) | 3 | 2 | find(2) | ? | 4->3->2->2 |
| 3 | Call find(2) | 2 | 2 | No recursion (root) | 2 | 4->3->2->2 |
| 4 | Return from find(2) | 2 | 2 | None | 2 | 4->3->2->2 |
| 5 | Set parent[3] = 2 | 3 | 2 | None | 2 | 4->3->2->2 |
| 6 | Return from find(3) | 3 | 2 | None | 2 | 4->3->2->2 |
| 7 | Set parent[4] = 2 | 4 | 3 | None | 2 | 4->2->2->2 |
| 8 | Return from find(4) | 4 | 2 | None | 2 | 4->2->2->2 |
| 9 | Final parent array | - | - | - | - | parent = [0,1,2,2,2] |
| Variable | Start | After Step 5 | After Step 7 | Final |
|---|---|---|---|---|
| parent[4] | 3 | 2 | 2 | 2 |
| parent[3] | 2 | 2 | 2 | 2 |
| parent[2] | 2 | 2 | 2 | 2 |
Path Compression in Union Find: - Used in find(x) to flatten tree. - If parent[x] != x, recursively find root. - Set parent[x] = root to shorten path. - Speeds up future find operations. - Key for efficient union-find performance.
path compression in the Union Find data structure?find operation locates the root parent of a node in Union Find.find operation by making nodes point directly to the root -> Option Bfind operation by making nodes point directly to the root [OK]find function with path compression in C++?parent[x] during recursion to root.parent[x] with recursive call result, implementing path compression correctly.int parent[5] = {0, 1, 2, 3, 4};
int find(int x) {
if(parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void unionSet(int a, int b) {
int rootA = find(a);
int rootB = find(b);
if(rootA != rootB) parent[rootB] = rootA;
}
unionSet(1, 2);
unionSet(2, 3);
find(3);
What is the state of the parent array after these operations?find function is intended to implement path compression but has a bug:
int find(int x) {
if(parent[x] == x) return x;
find(parent[x]);
return parent[x];
}
What is the bug in this code?find(parent[x]) is made but its result is not assigned back to parent[x].parent[x] remains unchanged, so path compression does not happen.parent[x] during recursion for compression -> Option Aparent[x] during recursion for compression [OK]unionSet(0, 1); unionSet(1, 2); unionSet(3, 4); unionSet(4, 5); find(2); find(5); unionSet(2, 5); find(5);After all operations, what is the parent array state assuming path compression is used in
find?Pass the test and this pattern moves unknown