# union-find

> which group is this in? merge groups and answer that in almost constant time.

source: https://learning.anthnydas.com/ds/union-find/

## tl;dr

each group is a tree of elements, every element pointing at its parent, and the root names the group. two elements are in the same group when they reach the same root. a union hangs one root under the other.

- **find:** O(α(n)) (amortized, under 5 for any real n)
- **union:** O(α(n)) (two finds and one link)
- **connected:** O(α(n)) (two finds, compare the roots)
- **tallest tree:** log2 n (with union by size alone)
- **split a group:** no way (a union can't be undone)
- **reach for it:** which parts of a graph are connected, kruskal's minimum spanning tree, finding a cycle in an undirected graph, grouping things that turn out equal, like accounts or equations, regions of an image, and percolation

union-find keeps elements in groups, and answers two questions: which group is this in, and are these two in the same one? each group is a tree in which every element points at its parent. the root is its own parent and names the group. find walks up to the root, and union joins two groups by hanging one root under the other. with two tricks, a long run of either costs almost nothing per step.

## the idea

> **interactive figure:** an animation in six steps, with the elements 0 to 7 drawn as a forest above their parent array. first all eight are roots, side by side, and each slot of the array holds its own index. then union(0, 1): both are roots, and 1 hangs under 0, so slot 1 now holds 0. then union(2, 3) hangs 3 under 2. then union(1, 3): a walk from 1 reaches its root 0 in cyan, a walk from 3 reaches 2 in amber; the two trees have 2 elements each, a tie, so 2 hangs under 0, taking 3 with it, and slot 2 holds 0. then find(3) walks up from 3 to 2 to 0. last, 3 is pointed straight at 0: it moves up next to 1 and 2, and slot 3 changes from 2 to 0.

eight elements, each in a group of its own. every element is its own parent, so each slot of the parent array holds its own index.

union(0, 1): both are roots. 1 goes under 0, and slot 1 now says 0.

union(2, 3): 3 goes under 2.

union(1, 3): find each root first. 1 leads to 0, and 3 leads to 2. both trees hold 2 elements, a tie, so the second root, 2, goes under the first. 3 comes along without being touched.

find(3): follow the parents up. 3's parent is 2, and 2's is 0, which is its own parent: the root, 2 links up.

on the way back, point 3 straight at 0. the next find from 3 takes 1 link. the forest and the array change together: the array is all there is.

## the easy part

find(x) follows parents from x until it reaches an element that is its own parent: the root. two elements are connected if their finds reach the same root. union(a, b) finds both roots, and if they differ, sets one root's parent to the other. that's the whole structure: one array of parents, plus a size for each root.

the trouble is how tall the trees get. hang roots carelessly, and a tree turns into a long chain, and every find walks all of it. two small rules fix that.

## the operations

> **interactive figure:** an interactive union-find of 8 elements, drawn as a forest above its parent array. type two elements, a and b, or tap nodes to fill them in, then union them, find a's root, or check whether they're connected. next in line unions 1 and 0, then 2 and 1, and so on, and random union picks a pair. two checkboxes turn union by size and path compression on and off. a find from a walks in cyan, one from b in amber, and an element whose parent changes is white, in the forest and the array at once. the matching pseudocode line is highlighted, with counts of the links followed, the sets and the tallest tree.

union 0 and 1, then 2 and 3, then 1 and 3. then reset, turn off union by size, and press next in line until the elements make a stick, 7 links tall. a find from 0 walks all of it, and with path compression on, it leaves every element pointing at the root.

## try it

> **interactive figure:** a practice exercise on a union-find forest drawn above its parent array. some questions union two elements and ask what one root's parent is after, or find an element and ask how many links it follows. others ask where an element points after a compressing find, or which element is the root of a set, answered by tapping the node.

## pseudocode

```text
find(u, x):
  root = x
  while u.parent[root] != root:  # up to the root
    root = u.parent[root]
  while u.parent[x] != root:  # then point the path at it
    next = u.parent[x]
    u.parent[x] = root
    x = next
  return root

union(u, a, b):
  ra, rb = find(u, a), find(u, b)
  if ra == rb: return false  # one set already
  if u.size[ra] < u.size[rb]: ra, rb = rb, ra
  u.parent[rb] = ra  # the smaller tree goes under
  u.size[ra] += u.size[rb]
  u.sets -= 1
  return true

connected(u, a, b):
  return find(u, a) == find(u, b)
```

find is two loops: one up to the root, and one that points every element on the way at it. a recursive find is shorter, and with union by size it never goes more than log2 n deep, but the loop needs no stack at all.

## union by size, up close

> **interactive figure:** three forests of the elements 0 to 7, joined the worst way union by size allows: always two groups of equal size. first four pairs, each 1 link deep. then two groups of four, 2 links deep. then one group of eight, where 7 sits 3 links below the root 0, and 3 is log2 of 8.

- **union by size.** keep a count of each tree's elements at its root, and hang the smaller tree under the bigger one. an element only gets one link deeper when its tree goes under a tree at least as big, so each time it does, its group at least doubles. that can happen at most log2 n times, so no element is ever more than log2 n links from its root[^algs4]
- **path compression.** a find already knows every element on its path, and where the root is. pointing them all straight at the root costs one more pass, and the next find from any of them is a single link
- **both together.** the amortized cost of an operation falls to the inverse ackermann function of n, which grows so slowly that it stays under 5 for any n that fits in a computer[^algs4]

the worst case for union by size is joining equal groups every time, as in the figure. 1024 elements joined that way end up 10 links tall: log2 of 1024.

## complexity

| operation | naive | by size  | both    |
| --------- | ----- | -------- | ------- |
| find      | O(n)  | O(log n) | O(α(n)) |
| union     | O(n)  | O(log n) | O(α(n)) |
| connected | O(n)  | O(log n) | O(α(n)) |

naive means hanging roots without looking at sizes, and never compressing. its trees can turn into chains as long as the group. the costs for both together are amortized: one find can still walk a long path, but it shortens that path for everyone after it.

> **interactive figure:** a line chart of the links a find follows, on average, against how many elements there are, from 16 to 4,096 on a doubling scale, over the same seeded run of unions of random pairs and finds of random elements. naive linking, in amber, climbs off the top of the chart, at 3 links, before 64 elements: 1.9 links at 16 and 223 at 4,096. union by size alone, dashed, stays near 1.3. path compression alone, dotted, creeps up to 2. both together, solid white, stays at about 0.8. a slider picks a size and reads off all four.

on 4,096 elements, half the operations unions of random pairs and half finds, naive linking averaged 223 links per find. union by size alone kept it to 1.33, path compression alone to 2.01, and the two together to 0.83.

## implementations

each tab is the real file from the repo, checked by its tests (`go test`, `cargo test`, `vitest`, `make test`, `swift test`, `python -m unittest`), including 2000 seeded unions, finds and checks against a plain list of labels, one per element, that a union relabels in full. after every one, each element d links from its root has to be in a group of at least 2^d. every tab hangs the smaller tree under the bigger one, and on a tie, b's root under a's, so the tests can check the parent array itself. typescript and python turn away an element out of range with an error. python has to check for itself, since a negative index counts from the end of a list. go, rust and swift stop when the index runs off the array, and c's header asks for elements below n.

`go/algos/unionfind/unionfind.go`

```go
// Package unionfind is a reference union-find over n elements, 0 to n - 1: which set is an element in, and
// merge two sets. union by size keeps every tree at most log2 n links tall, and path compression flattens
// each path it walks, so a long run of operations costs nearly constant time each. every walk is a loop.
package unionfind

import "slices"

// UnionFind keeps the elements 0 to n - 1 in sets. Each set is a tree: every element points at its
// parent, and the root points at itself.
type UnionFind struct {
	parent []int
	size   []int // the size of the tree under each element. only a root's is kept up to date
	sets   int
}

// New returns a union-find over n elements, each in a set of its own: every element is its own parent.
func New(n int) *UnionFind {
	uf := &UnionFind{parent: make([]int, n), size: make([]int, n), sets: n}
	for x := range n {
		uf.parent[x] = x
		uf.size[x] = 1
	}
	return uf
}

// Sets returns how many sets there are.
func (uf *UnionFind) Sets() int {
	return uf.sets
}

// Parents returns a copy of each element's parent. A root is its own parent.
func (uf *UnionFind) Parents() []int {
	return slices.Clone(uf.parent)
}

// Find returns the root of x's set: it follows parents up until one is its own. Then it points every
// node on that path straight at the root, so the next walk from any of them is one link.
func (uf *UnionFind) Find(x int) int {
	root := x
	for uf.parent[root] != root {
		root = uf.parent[root]
	}
	for uf.parent[x] != root {
		next := uf.parent[x] // save it: the next line overwrites it
		uf.parent[x] = root
		x = next
	}
	return root
}

// Union merges a's set and b's: the smaller tree's root goes under the bigger one's, and on a tie b's
// goes under a's. It returns false if they were in one set already.
func (uf *UnionFind) Union(a, b int) bool {
	ra, rb := uf.Find(a), uf.Find(b)
	if ra == rb {
		return false
	}
	if uf.size[ra] < uf.size[rb] {
		ra, rb = rb, ra // now ra is the bigger root, or a's on a tie
	}
	uf.parent[rb] = ra
	uf.size[ra] += uf.size[rb]
	uf.sets--
	return true
}

// Connected reports whether a and b are in one set: they have the same root.
func (uf *UnionFind) Connected(a, b int) bool {
	return uf.Find(a) == uf.Find(b)
}

// SetSize returns how many elements share x's set. Only a root's count is kept up to date.
func (uf *UnionFind) SetSize(x int) int {
	return uf.size[uf.Find(x)]
}
```

`rust/algos/src/union_find.rs`

```rust
//! union-find over n elements, 0 to n - 1: which set is an element in, and merge two sets. union by size keeps every tree at most log2 n links tall, and path compression flattens each path it walks, so a long run of operations costs nearly constant time each. every walk is a loop.

/// The elements 0 to n - 1, split into sets. Each set is a tree, and one parent array holds them
/// all: a root is its own parent and stands for its set. `connected` and `set_size` only ask, but
/// they take `&mut self`: every find flattens the path it walks. An element past n - 1 panics, as
/// any index out of range does: there's no check of its own.
pub struct UnionFind {
    parent: Vec<usize>,
    size: Vec<usize>,
    sets: usize,
}

impl UnionFind {
    /// Makes `n` elements, each in a set of its own: every element is its own parent.
    pub fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            size: vec![1; n],
            sets: n,
        }
    }

    /// How many sets there are.
    pub fn sets(&self) -> usize {
        self.sets
    }

    /// Each element's parent: `x`'s is at index `x`. A root is its own parent.
    pub fn parents(&self) -> &[usize] {
        &self.parent
    }

    /// The root of `x`'s set: follow parents up until one is its own. Then point every node on
    /// that path straight at the root, so the next walk from any of them is one link.
    pub fn find(&mut self, mut x: usize) -> usize {
        let mut root = x;
        while self.parent[root] != root {
            root = self.parent[root];
        }
        while self.parent[x] != root {
            let next = self.parent[x];
            self.parent[x] = root;
            x = next;
        }
        root
    }

    /// Merges `a`'s set and `b`'s: the smaller tree's root goes under the bigger one's, and on a
    /// tie `b`'s goes under `a`'s. False if they were in one set already.
    pub fn union(&mut self, a: usize, b: usize) -> bool {
        let mut ra = self.find(a);
        let mut rb = self.find(b);
        if ra == rb {
            return false;
        }
        if self.size[ra] < self.size[rb] {
            (ra, rb) = (rb, ra);
        }
        self.parent[rb] = ra;
        self.size[ra] += self.size[rb];
        self.sets -= 1;
        true
    }

    /// Whether `a` and `b` are in one set: they have the same root.
    pub fn connected(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    /// How many elements share `x`'s set. Only a root's count is kept up to date.
    pub fn set_size(&mut self, x: usize) -> usize {
        // not self.size[self.find(x)]: size would be borrowed while find changes self
        let root = self.find(x);
        self.size[root]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeSet;

    /// Links from `x` up to its root, read off the parent array without compressing anything.
    fn depth(parent: &[usize], mut x: usize) -> usize {
        let mut links = 0;
        while parent[x] != x {
            x = parent[x];
            links += 1;
        }
        links
    }

    #[test]
    fn starts_as_n_sets_of_one_every_element_is_its_own_parent() {
        let mut uf = UnionFind::new(8);
        assert_eq!(uf.parents(), [0, 1, 2, 3, 4, 5, 6, 7]);
        assert_eq!((uf.sets(), uf.find(5), uf.set_size(5)), (8, 5, 1));
        assert_eq!((uf.connected(3, 3), uf.connected(0, 1)), (true, false));
    }

    #[test]
    fn union_joins_two_sets_and_says_false_when_they_are_joined_already() {
        let mut uf = UnionFind::new(8);
        assert_eq!(
            (
                uf.union(0, 1),
                uf.sets(),
                uf.connected(0, 1),
                uf.connected(1, 0)
            ),
            (true, 7, true, true)
        );
        assert_eq!((uf.union(1, 0), uf.sets()), (false, 7));
    }

    #[test]
    fn the_smaller_trees_root_goes_under_the_bigger_ones() {
        let mut uf = UnionFind::new(8);
        uf.union(0, 1);
        // 2 is alone, 0 has 2 elements: 2 goes under 0, whatever the order
        assert!(uf.union(2, 0));
        assert_eq!(uf.parents()[..3], [0, 0, 0]);
        assert_eq!(uf.set_size(2), 3);
    }

    #[test]
    fn a_tie_bs_root_goes_under_as() {
        let mut uf = UnionFind::new(8);
        uf.union(0, 1);
        uf.union(2, 3);
        assert_eq!(uf.parents()[..4], [0, 0, 2, 2]);
        assert!(uf.union(1, 3));
        assert_eq!(uf.parents()[..4], [0, 0, 0, 2]);
    }

    #[test]
    fn find_points_every_node_on_the_path_at_the_root() {
        let mut uf = UnionFind::new(8);
        // pairs, then pairs of pairs, then the two halves: the tallest tree 8 elements can make,
        // 3 links deep
        for (a, b) in [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (4, 6), (0, 4)] {
            uf.union(a, b);
        }
        assert_eq!(uf.parents(), [0, 0, 0, 2, 0, 4, 4, 6]);
        assert_eq!(depth(uf.parents(), 7), 3);
        assert_eq!(uf.find(7), 0);
        assert_eq!(uf.parents(), [0, 0, 0, 2, 0, 4, 0, 0]);
        assert_eq!((uf.sets(), uf.set_size(3)), (1, 8));
    }

    #[test]
    fn union_by_size_1024_elements_joined_the_worst_way_are_10_links_tall_log2_of_1024() {
        let n = 1024;
        let mut uf = UnionFind::new(n);
        // equal halves every time, always joining two roots, so no find has a path to compress
        let mut half = 1;
        while half < n {
            for i in (0..n).step_by(2 * half) {
                uf.union(i, i + half);
            }
            half *= 2;
        }
        let parent = uf.parents();
        assert_eq!((0..n).map(|x| depth(parent, x)).max(), Some(10));
        assert_eq!((uf.sets(), uf.set_size(n - 1)), (1, n));
    }

    #[test]
    fn a_million_elements_joined_one_at_a_time_into_one_set() {
        let n = 1_000_000;
        let mut uf = UnionFind::new(n);
        for i in 1..n {
            uf.union(i - 1, i);
        }
        assert_eq!((uf.sets(), uf.find(n - 1), uf.set_size(0)), (1, 0, n));
    }

    #[test]
    fn agrees_with_a_label_per_element_over_2000_seeded_operations() {
        // xorshift32 seeded with 42, like the other tests here
        let mut state: u32 = 42;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        let n = 50;
        let mut uf = UnionFind::new(n);
        // the model: each element's set label, and a union relabels a whole set
        let mut label: Vec<usize> = (0..n).collect();
        for _ in 0..2000 {
            let a = next() % n;
            let b = next() % n;
            match next() % 4 {
                0 => {
                    let joined = label[a] != label[b];
                    assert_eq!(uf.union(a, b), joined);
                    if joined {
                        let (gone, kept) = (label[b], label[a]);
                        for l in &mut label {
                            if *l == gone {
                                *l = kept;
                            }
                        }
                    }
                }
                1 => assert_eq!(uf.connected(a, b), label[a] == label[b]),
                2 => assert_eq!(label[uf.find(a)], label[a]),
                _ => assert_eq!(
                    uf.set_size(a),
                    label.iter().filter(|&&l| l == label[a]).count()
                ),
            }
            assert_eq!(uf.sets(), label.iter().collect::<BTreeSet<_>>().len());
            // union by size: an element d links from its root is in a set of at least 2^d, since
            // it only gets deeper when its tree goes under one at least as big. finds only make
            // paths shorter
            let parent = uf.parents();
            for x in 0..n {
                let count = label.iter().filter(|&&l| l == label[x]).count();
                assert!(1 << depth(parent, x) <= count);
            }
        }
    }
}
```

`site/src/visuals/union-find/union-find.ts`

```ts
/**
 * Union-find over n elements, 0 to n - 1: which set is an element in, and merge two sets. Union by size keeps every
 * tree at most log2 n links tall, and path compression flattens each path it walks, so a long run of operations
 * costs nearly constant time each. Every walk is a loop.
 */
export class UnionFind {
  #parent: number[];
  #size: number[];
  #sets: number;

  /** n elements, each in a set of its own: every element is its own parent. */
  constructor(n: number) {
    this.#parent = Array.from({ length: n }, (_, i) => i);
    this.#size = Array<number>(n).fill(1);
    this.#sets = n;
  }

  /** How many sets there are. */
  get sets(): number {
    return this.#sets;
  }

  /** Each element's parent, a copy. A root is its own parent. */
  parents(): number[] {
    return [...this.#parent];
  }

  #check(x: number) {
    if (!Number.isInteger(x) || x < 0 || x >= this.#parent.length) throw new RangeError(`no element ${x}`);
  }

  /** The root of x's set: follow parents up until one is its own. Then point every node on that path straight at
   * the root, so the next walk from any of them is one link. */
  find(x: number): number {
    this.#check(x);
    let root = x;
    while (this.#parent[root] !== root) root = this.#parent[root];
    while (this.#parent[x] !== root) {
      const next = this.#parent[x];
      this.#parent[x] = root;
      x = next;
    }
    return root;
  }

  /** Merge a's set and b's: the smaller tree's root goes under the bigger one's, and on a tie b's goes under a's.
   * False if they were in one set already. */
  union(a: number, b: number): boolean {
    let ra = this.find(a);
    let rb = this.find(b);
    if (ra === rb) return false;
    if (this.#size[ra] < this.#size[rb]) [ra, rb] = [rb, ra];
    this.#parent[rb] = ra;
    this.#size[ra] += this.#size[rb];
    this.#sets -= 1;
    return true;
  }

  /** Whether a and b are in one set: they have the same root. */
  connected(a: number, b: number): boolean {
    return this.find(a) === this.find(b);
  }

  /** How many elements share x's set. Only a root's count is kept up to date. */
  setSize(x: number): number {
    return this.#size[this.find(x)];
  }
}
```

`c/algos/union_find.c`

```c
/* union-find over n elements, 0 to n - 1: which set is an element in, and merge two sets. union by size keeps every tree at most log2 n links tall, and path compression flattens each path it walks, so a long run of operations costs nearly constant time each. every walk is a loop. */
#include "union_find.h"

#include <stdlib.h>

/* n = 0 stops before the mallocs: malloc(0) can return NULL, which would look like a failure. if
   one malloc fails, uf_free frees the other (free(NULL) does nothing), so nothing is left behind */
bool uf_init(UnionFind *u, size_t n) {
    *u = (UnionFind){.n = n, .sets = n};
    if (n == 0) return true;
    u->parent = malloc(n * sizeof *u->parent);
    u->size = malloc(n * sizeof *u->size);
    if (!u->parent || !u->size) {
        uf_free(u);
        return false;
    }
    for (size_t x = 0; x < n; x++) {
        u->parent[x] = x;
        u->size[x] = 1;
    }
    return true;
}

void uf_free(UnionFind *u) {
    free(u->parent);
    free(u->size);
    *u = (UnionFind){0}; /* no elements and no sets */
}

/* two loops, no recursion. the first follows parents up until one is its own: the root. the second
   walks the same path again and points each node on it straight at the root, so the next find from
   any of them takes one link */
size_t uf_find(UnionFind *u, size_t x) {
    size_t root = x;
    while (u->parent[root] != root) root = u->parent[root];
    while (u->parent[x] != root) {
        size_t next = u->parent[x];
        u->parent[x] = root;
        x = next;
    }
    return root;
}

bool uf_union(UnionFind *u, size_t a, size_t b) {
    size_t ra = uf_find(u, a), rb = uf_find(u, b);
    if (ra == rb) return false; /* one set already */
    /* ra is to be the bigger root: on a tie nothing swaps, so b's root goes under a's. every
       element in the smaller tree gets one link deeper, and its set at least doubles, which can
       only happen log2 n times */
    if (u->size[ra] < u->size[rb]) {
        size_t t = ra;
        ra = rb;
        rb = t;
    }
    u->parent[rb] = ra;
    u->size[ra] += u->size[rb];
    u->sets--;
    return true;
}

bool uf_connected(UnionFind *u, size_t a, size_t b) {
    return uf_find(u, a) == uf_find(u, b);
}

/* only a root's size is kept up to date, so read it there */
size_t uf_set_size(UnionFind *u, size_t x) {
    return u->size[uf_find(u, x)];
}
```

`swift/algos/UnionFind.swift`

```swift
/// union-find over n elements, 0 to n - 1: which set is an element in, and merge two sets. union by size keeps every tree at most log2 n links tall, and path compression flattens each path it walks, so a long run of operations costs nearly constant time each. every walk is a loop.
/// a struct, since it's just two arrays and a count: copying the struct copies the sets. path compression writes to the parent array, so find, connected and setSize are all mutating.
public struct UnionFind {
    /// each element's parent. a root is its own parent
    public private(set) var parents: [Int]
    // a size per element, but only a root's is kept up to date: how many elements are in its set
    private var size: [Int]
    /// how many sets
    public private(set) var sets: Int

    /// n elements, each in a set of its own: every element is its own parent
    public init(_ n: Int) {
        parents = Array(0..<n)
        size = Array(repeating: 1, count: n)
        sets = n
    }

    /// the root of x's set: follow parents up until one is its own. then point every node on that path straight at
    /// the root, so the next walk from any of them is one link
    public mutating func find(_ x: Int) -> Int {
        var root = x
        while parents[root] != root { root = parents[root] }
        var node = x
        while parents[node] != root {
            let next = parents[node]
            parents[node] = root
            node = next
        }
        return root
    }

    /// merges a's set and b's: the smaller tree's root goes under the bigger one's, and on a tie b's goes under a's.
    /// false if they were in one set already
    @discardableResult
    public mutating func union(_ a: Int, _ b: Int) -> Bool {
        var ra = find(a)
        var rb = find(b)
        if ra == rb { return false }
        // a's tree has to be strictly smaller to swap: on a tie, b's root goes under a's
        if size[ra] < size[rb] { swap(&ra, &rb) }
        parents[rb] = ra
        size[ra] += size[rb]
        sets -= 1
        return true
    }

    /// whether a and b are in one set: they have the same root
    public mutating func connected(_ a: Int, _ b: Int) -> Bool {
        find(a) == find(b)
    }

    /// how many elements share x's set: the size kept at its root
    public mutating func setSize(_ x: Int) -> Int {
        size[find(x)]
    }
}
```

`python/algos/union_find.py`

```python
"""union-find over n elements, 0 to n - 1: which set is an element in, and merge two sets. union by size keeps every tree at most log2 n links tall, and path compression flattens each path it walks, so a long run of operations costs nearly constant time each. every walk is a loop."""

from __future__ import annotations


class UnionFind:
    """Elements 0 to n - 1, split into sets.

    Each set is a tree: every element points at its parent, and the root points at itself.
    """

    def __init__(self, n: int) -> None:
        self._parent = list(range(n))  # every element starts as its own parent: n sets of one
        self._size = [1] * n  # the size of the tree under each element. only a root's is kept up to date
        self._sets = n

    @property
    def sets(self) -> int:
        """How many sets there are."""
        return self._sets

    def parents(self) -> list[int]:
        """Return a copy of each element's parent. A root is its own parent."""
        return list(self._parent)

    def find(self, x: int) -> int:
        """Return the root of x's set: follow parents up until one is its own.

        Then point every node on that path straight at the root, so the next walk from any of them
        is one link.
        """
        parent = self._parent
        if not 0 <= x < len(parent):
            raise IndexError(f"no element {x}")  # a negative index would count from the end of the list
        root = x
        while parent[root] != root:
            root = parent[root]
        while parent[x] != root:
            nxt = parent[x]  # save it: the next line overwrites it
            parent[x] = root
            x = nxt
        return root

    def union(self, a: int, b: int) -> bool:
        """Merge a's set and b's. Return False if they were in one set already.

        The smaller tree's root goes under the bigger one's, and on a tie b's goes under a's.
        """
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self._size[ra] < self._size[rb]:
            ra, rb = rb, ra  # now ra is the bigger root, or a's on a tie
        self._parent[rb] = ra
        self._size[ra] += self._size[rb]
        self._sets -= 1
        return True

    def connected(self, a: int, b: int) -> bool:
        """Return True if a and b are in one set: they have the same root."""
        return self.find(a) == self.find(b)

    def set_size(self, x: int) -> int:
        """Return how many elements share x's set. Only a root's count is kept up to date."""
        return self._size[self.find(x)]
```

## pitfalls

- **linking the elements, not their roots.** union(a, b) has to set a root's parent. setting a's parent to b cuts a's subtree out of its group
- **no union by size.** without it, unions in an unlucky order make a chain, and every find walks it
- **a size that's out of date.** only a root's count is kept up to date. after a union, the old root's count means nothing
- **the root isn't a fixed name.** a union can turn a root into an ordinary element. to compare groups, compare roots found after the last union
- **no splitting.** union-find can merge groups but never split one. removing an edge from a graph needs a different structure

## variants

- **union by rank.** keep each root's height bound instead of its size, and hang the lower tree under the higher. the guarantees are the same. petgraph and ena both do this[^petgraph][^ena]
- **path halving and path splitting.** one pass instead of two: point every element, or every other one, at its grandparent as the find walks up. the amortized bound is the same[^algs4]. petgraph's find with compression is path splitting[^petgraph]
- **union-find with undo.** without compression, each union changes one parent, so a log of changes can roll them back. ena takes snapshots this way, for backtracking[^ena]
- **weighted union-find.** each element also stores its offset from its parent, so the structure can answer how much bigger a is than b, not just whether they're related

## practice

- [number of provinces](https://leetcode.com/problems/number-of-provinces/): count the groups
- [redundant connection](https://leetcode.com/problems/redundant-connection/): the first edge whose ends are already connected
- [number of operations to make network connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/): groups and spare edges
- [accounts merge](https://leetcode.com/problems/accounts-merge/): union by a shared email
- [satisfiability of equality equations](https://leetcode.com/problems/satisfiability-of-equality-equations/): union the equals, then check the not-equals
- [most stones removed with same row or column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/): union rows with columns

## how real libraries do it

- **rust.** rustc's union-find lives in its own crate, ena: tarjan's algorithm with a rank on each root, path compression, and snapshots it can roll back to[^ena]
- **petgraph.** `UnionFind` joins by rank, and its find with compression points each element at its grandparent. its kruskal's minimum spanning tree is built on it[^petgraph]
- **networkx.** `UnionFind` keeps a weight per root, the group's size, hangs lighter roots under the heaviest, and compresses each path it walks[^networkx]
- **the standard libraries.** none of python, go, rust, java, swift or c has one. it's short enough that most code writes its own

[^algs4]: [union-find](https://algs4.cs.princeton.edu/15uf/), section 1.5 of sedgewick and wayne's _algorithms_, 4th edition: weighted quick-union always connects the smaller tree to the larger, and the depth of any node it builds for n sites is at most lg n. with path compression added, the amortized cost per operation is bounded by the inverse ackermann function, and the exercises note the same bound for path halving and path splitting.

[^ena]: [unify/mod.rs](https://github.com/rust-lang/ena/blob/v0.14.0/src/unify/mod.rs#L154-L176) in ena 0.14.0, whose [readme](https://github.com/rust-lang/ena/blob/v0.14.0/README.md) calls it an implementation of union-find extracted from, and used by, rustc: tarjan's union-find, with a rank on each root to keep it balanced, and `snapshot` and `rollback_to` for backtracking. [its root lookup](https://github.com/rust-lang/ena/blob/v0.14.0/src/unify/mod.rs#L350-L352) uses path compression.

[^petgraph]: [unionfind.rs](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/unionfind.rs#L144-L153) in petgraph 0.8.3: `find_mut` writes each element's grandparent into its parent as it walks up, and [`union`](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/unionfind.rs#L206-L215) puts the smaller rank below the larger. its [minimum spanning tree](https://github.com/petgraph/petgraph/blob/petgraph%40v0.8.3/src/algo/min_spanning_tree.rs#L14-L19) uses kruskal's algorithm, with a `UnionFind` of the subgraphs.

[^networkx]: [union_find.py](https://github.com/networkx/networkx/blob/networkx-3.7/networkx/utils/union_find.py#L55-L106) in networkx 3.7: a find collects the path to the root, then points every element on it at the root, and a union hangs the other roots under the heaviest one, adding their weights. it's based on josiah carlson's code, with changes by david eppstein.

## related

- https://learning.anthnydas.com/ds/graph.md
- https://learning.anthnydas.com/ds/trie.md
- https://learning.anthnydas.com/ds/bst.md
- https://learning.anthnydas.com/ds/hash-table.md
