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, and update x's parent directly to root to flatten the tree.
func find(x int) int { 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) | ? | parent[4] points to 3 |
| 2 | Call find(3) | 3 | 1 | find(1) | ? | parent[3] points to 1 |
| 3 | Call find(1) | 1 | 1 | No recursive call | 1 | parent[1] points to itself (root) |
| 4 | Return from find(1) | 1 | 1 | - | 1 | No change |
| 5 | Set parent[3] = 1 | 3 | 1 | - | 1 | parent[3] updated to 1 (no change) |
| 6 | Return from find(3) | 3 | 1 | - | 1 | No change |
| 7 | Set parent[4] = 1 | 4 | 3 | - | 1 | parent[4] updated to 1 (path compressed) |
| 8 | Return from find(4) | 4 | 1 | - | 1 | No change |
| 9 | Final root returned | 4 | 1 | - | 1 | Root of 4 is 1 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 7 | 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 |
Path Compression in Union Find: - find(x) returns root of x - If parent[x] != x, recursively find root - Update parent[x] = root to flatten tree - Speeds up future find calls - Key: recursion + pointer update
path compression in the Union Find data structure?find operation to flatten the tree structure by making nodes point directly to the root.find operation by making nodes point directly to the root -> Option Afind operation by making nodes point directly to the root [OK]find function with path compression in Union Find?parent[x] to the root, which is path compression.parent[x]. func find(parent []int, x int) int { parent[x] = x; return x } wrongly resets parent[x] to itself always.package main
import "fmt"
func find(parent []int, x int) int {
if parent[x] != x {
parent[x] = find(parent, parent[x])
}
return parent[x]
}
func main() {
parent := []int{0, 1, 2, 3, 4}
parent[1] = 0
parent[2] = 1
fmt.Println(find(parent, 2))
fmt.Println(parent)
}find with path compression:
func find(parent []int, x int) int {
if parent[x] == x {
return x
}
parent[x] = find(parent, x)
return parent[x]
}find(parent, x), which causes infinite recursion because x does not change.find(parent, parent[x]) to move up the tree towards the root.find(parent, parent[x]) instead of find(parent, x) -> Option Cfind(parent, parent[x]) instead of find(parent, x) [OK]parent = [0, 0, 1, 2, 3], what will be the parent array after calling find(parent, 4) with path compression?Pass the test and this pattern moves unknown