Concept Flow - Path Compression in Union Find
Start: Find(x)
Is parent[x
No
Recursively find parent of parent[x
Set parent[x
Return root
Path Compression flattens the tree by making each node point directly to the root during find operation.
function find(x: number): number {
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) | TBD | parent[4] points to 3 |
| 2 | Call find(3) | 3 | 1 | find(1) | TBD | parent[3] points to 1 |
| 3 | Call find(1) | 1 | 1 | No recursion | 1 | parent[1] points to itself (root) |
| 4 | Return from find(1) | 3 | 1 | - | 1 | parent[3] updated to 1 (path compressed) |
| 5 | Return from find(3) | 4 | 3 | - | 1 | parent[4] updated to 1 (path compressed) |
| 6 | Final return | 4 | 1 | - | 1 | Root of 4 is 1, path compressed |
| 7 | Call find(5) | 5 | 5 | No recursion | 5 | parent[5] points to itself (root) |
| 8 | Final return | 5 | 5 | - | 5 | Root of 5 is 5 |
| Variable | Start | After Step 1 | After Step 2 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|---|
| parent[4] | 3 | 3 | 3 | 3 | 1 | 1 |
| parent[3] | 1 | 1 | 1 | 1 | 1 | 1 |
| parent[1] | 1 | 1 | 1 | 1 | 1 | 1 |
| parent[5] | 5 | 5 | 5 | 5 | 5 | 5 |
Path Compression in Union Find: - Used in find(x) to flatten tree. - If parent[x] != x, recursively find root. - Set parent[x] = root to compress path. - Speeds up future find operations. - Stops recursion when parent[x] == x.