Lesson contents

Disjoint sets and union–find

Union–find keeps track of which items belong to the same group. A find follows parent links to a representative. A union joins two groups.

Simple example

Join 1 with 2 and 3 with 4, then join 2 with 3. Print 1 if 1 and 4 now have the same representative.

Start1—2 3—4
Result1
main.rs
fn main() {
    let mut parent: [i64; 4] = [0, 1, 2, 3];
    let first: [i64; 3] = [0, 2, 1];
    let second: [i64; 3] = [1, 3, 2];
    let mut i: i64 = 0;
    while i < 3 {
        let mut a: i64 = first[(i) as usize];
        let mut b: i64 = second[(i) as usize];
        while parent[(a) as usize] != a {
            a = parent[(a) as usize];
        }
        while parent[(b) as usize] != b {
            b = parent[(b) as usize];
        }
        parent[(b) as usize] = a;
        i += 1;
    }
    let mut root: i64 = 3;
    while parent[(root) as usize] != root {
        root = parent[(root) as usize];
    }
    if root == parent[0] {
        println!("{}", 1);
    }
}
Output
1
Advertisements

Everyday examples

Merge project teams

A and B are a team. C and D are another. B teams up with C. Are A and D now connected?

StartA—B C—D
ResultA—B—C—D

Join the representatives of the two teams. A and D now reach the same representative.

Avoid a redundant cable

Roadside sensors 1, 2 and 3 are already connected through one another. Does a new cable from 1 to 3 connect a new group?

Start1—2—3
Result0

Both endpoints already have the same representative. The extra cable adds no new connection between groups.

Count connected tables

A hall starts with four separate tables. Join 1 to 2, then join 2 to 1 again. How many groups remain?

Start1 2 3 4
Result3

Only the first join merges two distinct groups. Repeating it must not reduce the count again.

Cost and limits

Union by size or rank plus path compression makes repeated operations nearly constant on average. Ordinary union–find cannot split a group when a link is removed.