Bird
Raised Fist0
DSA Rustprogramming~20 mins

Union Find Disjoint Set Data Structure in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Union Find Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output after union operations?
Consider a Union Find structure initialized with 5 elements (0 to 4). After performing union(0, 1), union(1, 2), and union(3, 4), what is the parent array representing the sets?
DSA Rust
struct UnionFind {
    parent: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> Self {
        Self { parent: (0..size).collect() }
    }

    fn find(&mut self, x: usize) -> usize {
        if self.parent[x] != x {
            self.parent[x] = self.find(self.parent[x]);
        }
        self.parent[x]
    }

    fn union(&mut self, x: usize, y: usize) {
        let px = self.find(x);
        let py = self.find(y);
        if px != py {
            self.parent[py] = px;
        }
    }
}

fn main() {
    let mut uf = UnionFind::new(5);
    uf.union(0, 1);
    uf.union(1, 2);
    uf.union(3, 4);
    println!("{:?}", uf.parent);
}
A[0, 0, 0, 3, 3]
B[0, 1, 2, 3, 4]
C[1, 1, 1, 4, 4]
D[0, 0, 1, 3, 3]
Attempts:
2 left
💡 Hint
Remember that union sets the parent of one root to the other root.
❓ Predict Output
intermediate
2:00remaining
What is the output of find with path compression?
Given the Union Find parent array [0, 0, 1, 3, 3], what will be the parent array after calling find(2) with path compression?
DSA Rust
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, 3, 3] };
    uf.find(2);
    println!("{:?}", uf.parent);
}
A[0, 0, 1, 3, 4]
B[0, 0, 0, 3, 3]
C[0, 1, 1, 3, 3]
D[0, 0, 2, 3, 3]
Attempts:
2 left
💡 Hint
Path compression updates the parent of the node to its root.
❓ Predict Output
advanced
2:00remaining
What is the output after union by rank?
Consider a Union Find with rank optimization. Initially, parent = [0,1,2,3], rank = [0,0,0,0]. After union(0,1), union(2,3), union(1,3), what are the parent and rank arrays?
DSA Rust
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> Self {
        Self {
            parent: (0..size).collect(),
            rank: vec![0; size],
        }
    }

    fn find(&mut self, x: usize) -> usize {
        if self.parent[x] != x {
            self.parent[x] = self.find(self.parent[x]);
        }
        self.parent[x]
    }

    fn union(&mut self, x: usize, y: usize) {
        let px = self.find(x);
        let py = self.find(y);
        if px != py {
            if self.rank[px] < self.rank[py] {
                self.parent[px] = py;
            } else if self.rank[px] > self.rank[py] {
                self.parent[py] = px;
            } else {
                self.parent[py] = px;
                self.rank[px] += 1;
            }
        }
    }
}

fn main() {
    let mut uf = UnionFind::new(4);
    uf.union(0, 1);
    uf.union(2, 3);
    uf.union(1, 3);
    println!("parent: {:?}", uf.parent);
    println!("rank: {:?}", uf.rank);
}
Aparent: [0, 0, 0, 0], rank: [2, 0, 0, 0]
Bparent: [0, 1, 2, 3], rank: [0, 0, 0, 0]
Cparent: [0, 0, 2, 2], rank: [1, 0, 1, 0]
Dparent: [0, 0, 0, 2], rank: [1, 0, 0, 0]
Attempts:
2 left
💡 Hint
Union by rank attaches smaller tree under bigger tree and increments rank only when ranks are equal.
🔧 Debug
advanced
2:00remaining
Identify the bug in this union find implementation
What error will this code produce when calling union(0, 1) twice?
DSA Rust
struct UnionFind {
    parent: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> Self {
        Self { parent: (0..size).collect() }
    }

    fn find(&mut self, x: usize) -> usize {
        if self.parent[x] != x {
            self.find(self.parent[x])
        } else {
            x
        }
    }

    fn union(&mut self, x: usize, y: usize) {
        let px = self.find(x);
        let py = self.find(y);
        if px != py {
            self.parent[py] = px;
        }
    }
}

fn main() {
    let mut uf = UnionFind::new(2);
    uf.union(0, 1);
    uf.union(0, 1);
    println!("{:?}", uf.parent);
}
AStack overflow due to infinite recursion in find
BNo error, output: [0, 0]
CIndex out of bounds error
DCompilation error due to missing return
Attempts:
2 left
💡 Hint
Check the find function's recursive call and its return value.
🚀 Application
expert
2:00remaining
How many connected components after unions?
You have 7 elements (0 to 6). You perform unions: union(0,1), union(1,2), union(3,4), union(5,6). How many connected components remain?
DSA Rust
struct UnionFind {
    parent: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> Self {
        Self { parent: (0..size).collect() }
    }

    fn find(&mut self, x: usize) -> usize {
        if self.parent[x] != x {
            self.parent[x] = self.find(self.parent[x]);
        }
        self.parent[x]
    }

    fn union(&mut self, x: usize, y: usize) {
        let px = self.find(x);
        let py = self.find(y);
        if px != py {
            self.parent[py] = px;
        }
    }

    fn count_components(&mut self) -> usize {
        let mut roots = std::collections::HashSet::new();
        for i in 0..self.parent.len() {
            roots.insert(self.find(i));
        }
        roots.len()
    }
}

fn main() {
    let mut uf = UnionFind::new(7);
    uf.union(0, 1);
    uf.union(1, 2);
    uf.union(3, 4);
    uf.union(5, 6);
    println!("{}", uf.count_components());
}
A2
B4
C3
D5
Attempts:
2 left
💡 Hint
Count how many groups are formed after unions.

Practice

(1/5)
1. What is the primary purpose of the Union Find Disjoint Set data structure?
easy
A. To sort elements in ascending order
B. To efficiently track and merge groups of connected elements
C. To store key-value pairs for fast lookup
D. To implement a queue with priority

Solution

  1. Step 1: Understand the role of Union Find

    The Union Find data structure is designed to keep track of which elements belong to which groups or sets, especially when these groups merge.
  2. Step 2: Compare with other data structures

    Sorting, key-value storage, and priority queues serve different purposes unrelated to grouping connected components.
  3. Final Answer:

    To efficiently track and merge groups of connected elements -> Option B
  4. Quick Check:

    Union Find = Group tracking [OK]
Hint: Union Find = fast group merging and checking [OK]
Common Mistakes:
  • Confusing Union Find with sorting algorithms
  • Thinking it stores key-value pairs
  • Mixing it up with priority queues
2. Which of the following is the correct Rust syntax to create a new Union Find structure for 5 elements using the union_find crate?
easy
A. let uf = UnionFind::create(5);
B. let uf = UnionFind::init(5);
C. let uf = new UnionFind(5);
D. let uf = UnionFind::new(5);

Solution

  1. Step 1: Recall Rust struct instantiation

    In Rust, constructors are usually implemented as associated functions named new, called with ::new().
  2. Step 2: Check common method names

    Methods like create, init, or using new as a keyword are not standard Rust patterns.
  3. Final Answer:

    let uf = UnionFind::new(5); -> Option D
  4. Quick Check:

    Rust constructors use ::new() [OK]
Hint: Rust constructors use ::new() method [OK]
Common Mistakes:
  • Using 'new' as a keyword instead of method
  • Using non-standard method names like create or init
  • Incorrect syntax like missing 'let' or wrong function call
3. Consider this Rust code using a Union Find structure with 4 elements (0 to 3):
let mut uf = UnionFind::new(4);
uf.union(0, 1);
uf.union(2, 3);
let connected = uf.equiv(1, 3);
println!("{}", connected);

What is the printed output?
medium
A. false
B. true
C. 1
D. Compilation error

Solution

  1. Step 1: Analyze union operations

    Elements 0 and 1 are connected, and elements 2 and 3 are connected, but these two groups are separate.
  2. Step 2: Check equivalence of 1 and 3

    Since 1 is in the first group and 3 in the second, they are not connected, so uf.equiv(1, 3) returns false.
  3. Final Answer:

    false -> Option A
  4. Quick Check:

    Groups: {0,1} and {2,3}, 1 and 3 not connected [OK]
Hint: Check if elements share the same root to confirm connection [OK]
Common Mistakes:
  • Assuming union connects all elements globally
  • Confusing union with adding elements
  • Expecting true without checking groups
4. The following Rust code snippet using Union Find has a bug. What is the error?
let mut uf = UnionFind::new(3);
uf.union(0, 1);
uf.union(1, 3);
medium
A. No error, code runs fine
B. Syntax error in union method call
C. Index out of bounds error due to invalid element 3
D. Logical error: union does not merge sets

Solution

  1. Step 1: Check the size of Union Find

    The Union Find is created for 3 elements indexed 0, 1, and 2.
  2. Step 2: Analyze union calls

    The call uf.union(1, 3) tries to access element 3, which is out of range and causes an index error.
  3. Final Answer:

    Index out of bounds error due to invalid element 3 -> Option C
  4. Quick Check:

    Union Find size 3 means max index 2 [OK]
Hint: Check element indices are within Union Find size [OK]
Common Mistakes:
  • Ignoring index range and assuming union works
  • Thinking union method syntax is wrong
  • Assuming no error occurs with invalid indices
5. You have 6 elements (0 to 5) initially disconnected. After these operations:
uf.union(0, 1);
uf.union(1, 2);
uf.union(3, 4);
uf.union(4, 5);
uf.union(2, 5);

How many distinct groups remain?
hard
A. 1
B. 2
C. 3
D. 4

Solution

  1. Step 1: Track unions step-by-step

    Union(0,1) connects 0 and 1; Union(1,2) connects 2 to that group; Union(3,4) connects 3 and 4; Union(4,5) connects 5 to that group.
  2. Step 2: Final union merges groups

    Union(2,5) connects the group {0,1,2} with {3,4,5}, merging all into one group.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    All elements connected after last union [OK]
Hint: Last union merges all groups into one [OK]
Common Mistakes:
  • Counting groups before last union
  • Not merging transitive connections
  • Assuming unions only connect pairs, not groups
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard