Union Find With Path Compression (Rust)

Implement a Rust disjoint set union find with path compression and union by rank for near constant amortized time.

RustData Integrity

Code

rustsnippet
11 lines
struct UnionFind { parent: Vec<usize>, rank: Vec<usize>, count: usize }
impl UnionFind {
    fn new(n: usize) -> Self { Self { parent: (0..n).collect(), rank: vec![0; n], count: n } }
    fn find(&mut self, mut x: usize) -> usize { while self.parent[x] != x { self.parent[x] = self.parent[self.parent[x]]; x = self.parent[x]; } x }
    fn union(&mut self, a: usize, b: usize) -> bool {
        let (ra, rb) = (self.find(a), self.find(b));
        if ra == rb { return false; }
        if self.rank[ra] < self.rank[rb] { self.parent[ra] = rb; } else if self.rank[ra] > self.rank[rb] { self.parent[rb] = ra; } else { self.parent[rb] = ra; self.rank[ra] += 1; }
        self.count -= 1; true
    }
}

How the snippet works

Union Find With Path Compression (Rust) is built around the functions new, find and union.

Applying it

The main signature reads fn new(n: usize) -> Self

Import new from the file and call it — the rest of the code is implementation detail.

Statements that matter

fn new(n: usize) -> Self { Self { parent: (0..n).collect(), rank: vec![0; n], count: n } }
if ra == rb { return false; }

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `new`, `find`, `union` at load time.