Concept Flow - Path Compression in Union Find
Start: Find(x)
Is parent[x
Return x
Set parent[x
Return root
Path compression flattens the tree by making each node point directly to the root during find operation.
fn find(x: usize, parent: &mut Vec<usize>) -> usize {
if parent[x] != x {
parent[x] = find(parent[x], parent);
}
parent[x]
}| Step | Operation | Node x | parent[x] before | Recursive call | parent[x] after | Visual State |
|---|---|---|---|---|---|---|
| 1 | Call find(3) | 3 | 1 | find(1) | 1 | parent = [0, 2, 2, 1, 4] |
| 2 | Call find(1) | 1 | 2 | find(2) | 2 | parent = [0, 2, 2, 1, 4] |
| 3 | Call find(2) | 2 | 2 | No recursion (root) | 2 | parent = [0, 2, 2, 1, 4] |
| 4 | Return from find(2) | 1 | 2 | Set parent[1] = 2 | 2 | parent = [0, 2, 2, 1, 4] |
| 5 | Return from find(1) | 3 | 1 | Set parent[3] = 2 | 2 | parent = [0, 2, 2, 2, 4] |
| 6 | Final return | 3 | 2 | Return 2 | 2 | parent = [0, 2, 2, 2, 4] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|---|---|
| parent[3] | 1 | 1 | 1 | 1 | 1 | 2 | 2 |
| parent[1] | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
| parent[2] | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
| parent vector | [0,2,2,1,4] | [0,2,2,1,4] | [0,2,2,1,4] | [0,2,2,1,4] | [0,2,2,1,4] | [0,2,2,2,4] | [0,2,2,2,4] |
Path Compression in Union Find: - Used in find operation to flatten tree. - Recursively find root of x. - Set parent[x] directly to root on return. - Speeds up future find calls. - Keeps tree shallow for efficiency.
path compression in the Union Find data structure?find operation to make the tree flatter by pointing nodes directly to the root.find calls, making them faster.find operations by flattening the tree -> Option Bfind [OK]find method with path compression in a Union Find struct?self must be mutable reference &mut self.usize.uf.find(3)?
struct UnionFind {
parent: Vec<usize>,
}
impl UnionFind {
fn find(&mut self, x: usize) -> usize {
if self.parent[x] != x {
self.parent[x] = self.find(self.parent[x]);
}
self.parent[x]
}
}
fn main() {
let mut uf = UnionFind { parent: vec![0, 0, 1, 2] };
let root = uf.find(3);
println!("{}", root);
}find method with path compression and select the correct fix:
fn find(&mut self, x: usize) -> usize {
if self.parent[x] == x {
self.parent[x] = self.find(self.parent[x]);
}
self.parent[x]
}self.parent[x] == x means x is root, so no recursion needed. The code wrongly recurses when x is root.self.parent[x] != x.parent = [0,1,2,3,4]. After performing unions union(0,1), union(1,2), and union(3,4), what will be the parent array after calling find(2) with path compression if unions always attach the second root to the first root?Pass the test and this pattern moves unknown