What is the main purpose of path compression in Union Find?
Path compression speeds up the find operation by making nodes on the path point directly to the root, flattening the structure for faster future queries.
Click to reveal answer
beginner
In Union Find, what does the find function return?
The find function returns the root or representative element of the set that a given element belongs to.
Click to reveal answer
intermediate
How does path compression affect the tree structure in Union Find?
It flattens the tree by making every node on the find path point directly to the root, reducing the tree height and speeding up future operations.
Click to reveal answer
intermediate
Why is path compression important for the efficiency of Union Find?
Because it reduces the time complexity of find operations almost to constant time, making Union Find very efficient for many union and find queries.
Click to reveal answer
intermediate
Show a simple Rust code snippet for the find function with path compression in Union Find.
Initial parent: [0, 0, 1, 2]. Element 3 points to 2, 2 points to 1, 1 points to 0.
Step 2: Perform find(3) with path compression
find(3) calls find(2), which calls find(1), which calls find(0). Since 0 is its own parent, root is 0. Path compression sets parent[3] = 0 and parent[2] = 0.
Final Answer:
0 -> Option D
Quick Check:
Root of 3 after compression = 0 [OK]
Hint: Follow parent chain until self-parent, update parents [OK]
Common Mistakes:
Stopping at immediate parent without recursion
Not updating parent during compression
Confusing indices with values
4. Identify the bug in this Rust 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]
}
medium
A. Change == to != in the if condition
B. Remove the recursive call inside if
C. Return self.parent[self.parent[x]] instead
D. Add a loop instead of recursion
Solution
Step 1: Analyze the if condition logic
The condition self.parent[x] == x means x is root, so no recursion needed. The code wrongly recurses when x is root.
Step 2: Correct the condition
It should recurse only if x is not root, so condition must be self.parent[x] != x.
Final Answer:
Change == to != in the if condition -> Option A
Quick Check:
Recurse only if not root [OK]
Hint: Recurse only when parent differs from node [OK]
Common Mistakes:
Recursing when node is root
Forgetting base case
Misusing equality in condition
5. You have a Union Find with 5 elements initialized as 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?