Interactive LabRuns in your browser

Union-Find (Disjoint Set)

Disjoint set union simulator comparing rank union and path compression.

Every element starts as its own set: parent[i] = i.
0r=01r=02r=03r=04r=05r=06r=07r=08r=09r=0
Sets: 10Tallest tree: 0Arrows are parent pointers; r = rank (upper bound on height).
i0123456789
parent0123456789

About this tool

Union-find (disjoint set union, DSU) tracks a collection of non-overlapping sets and answers one question very fast: are these two elements in the same set? Each set is a tree of parent pointers whose root is the set’s representative. find(x) walks up to the root; union(x, y) links one root under the other.

Two small optimizations make it almost constant time: union by rank attaches the shorter tree under the taller one, and path compression points every node on a find path directly at the root. This lab lets you switch each one on and off and watch the trees — and the tallest-tree counter — change.

How to use Union-Find (Disjoint Set)

  1. Start with every element in its own set. Enter two elements and click Union, or one element and click Find.
  2. Watch the parent arrows: union draws a new arrow from one root to the other; find highlights the path to the root.
  3. Turn off both optimizations and use “Build a worst-case chain” to create a tall tree.
  4. Turn path compression on and run find(0): the whole chain collapses into a star.

Examples

Union by rank

Input
union(1, 2), union(3, 4), union(1, 3)
Result
Both trees have rank 1, so one root goes under the other and that root’s rank becomes 2

Path compression

Input
Chain 0→1→2→3→4, find(0)
Result
Returns 4; afterwards 0, 1, 2 and 3 all point directly to 4

Implementation in five languages

The same algorithm in Python, JavaScript, Java, Go and C++. Each program is complete and runnable; the comments show what it prints.

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
        self.count = n                      # number of disjoint sets

    def find(self, x):
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:       # path compression
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                    # already connected
        if self.rank[ra] < self.rank[rb]:   # union by rank
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        self.count -= 1
        return True


uf = UnionFind(6)
uf.union(0, 1)
uf.union(2, 3)
uf.union(1, 3)
print(uf.find(0) == uf.find(2))   # True
print(uf.find(0) == uf.find(4))   # False
print(uf.union(0, 3))             # False: would create a cycle
print(uf.count)                   # 3  ({0,1,2,3}, {4}, {5})
class UnionFind {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i);
    this.rank = new Array(n).fill(0);
    this.count = n; // number of disjoint sets
  }

  find(x) {
    let root = x;
    while (this.parent[root] !== root) root = this.parent[root];
    while (this.parent[x] !== root) { // path compression
      const next = this.parent[x];
      this.parent[x] = root;
      x = next;
    }
    return root;
  }

  union(a, b) {
    let ra = this.find(a), rb = this.find(b);
    if (ra === rb) return false; // already connected
    if (this.rank[ra] < this.rank[rb]) [ra, rb] = [rb, ra]; // union by rank
    this.parent[rb] = ra;
    if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
    this.count--;
    return true;
  }
}

const uf = new UnionFind(6);
uf.union(0, 1);
uf.union(2, 3);
uf.union(1, 3);
console.log(uf.find(0) === uf.find(2)); // true
console.log(uf.find(0) === uf.find(4)); // false
console.log(uf.union(0, 3)); // false: would create a cycle
console.log(uf.count); // 3  ({0,1,2,3}, {4}, {5})
public class Main {
    static class UnionFind {
        private final int[] parent, rank;
        int count;  // number of disjoint sets

        UnionFind(int n) {
            parent = new int[n];
            rank = new int[n];
            count = n;
            for (int i = 0; i < n; i++) parent[i] = i;
        }

        int find(int x) {
            int root = x;
            while (parent[root] != root) root = parent[root];
            while (parent[x] != root) {          // path compression
                int next = parent[x];
                parent[x] = root;
                x = next;
            }
            return root;
        }

        boolean union(int a, int b) {
            int ra = find(a), rb = find(b);
            if (ra == rb) return false;          // already connected
            if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; }  // union by rank
            parent[rb] = ra;
            if (rank[ra] == rank[rb]) rank[ra]++;
            count--;
            return true;
        }
    }

    public static void main(String[] args) {
        UnionFind uf = new UnionFind(6);
        uf.union(0, 1);
        uf.union(2, 3);
        uf.union(1, 3);
        System.out.println(uf.find(0) == uf.find(2));  // true
        System.out.println(uf.find(0) == uf.find(4));  // false
        System.out.println(uf.union(0, 3));            // false: would create a cycle
        System.out.println(uf.count);                  // 3  ({0,1,2,3}, {4}, {5})
    }
}
package main

import "fmt"

type UnionFind struct {
	parent, rank []int
	Count        int // number of disjoint sets
}

func NewUnionFind(n int) *UnionFind {
	uf := &UnionFind{parent: make([]int, n), rank: make([]int, n), Count: n}
	for i := range uf.parent {
		uf.parent[i] = i
	}
	return uf
}

func (uf *UnionFind) Find(x int) int {
	root := x
	for uf.parent[root] != root {
		root = uf.parent[root]
	}
	for uf.parent[x] != root { // path compression
		uf.parent[x], x = root, uf.parent[x]
	}
	return root
}

func (uf *UnionFind) Union(a, b int) bool {
	ra, rb := uf.Find(a), uf.Find(b)
	if ra == rb {
		return false // already connected
	}
	if uf.rank[ra] < uf.rank[rb] { // union by rank
		ra, rb = rb, ra
	}
	uf.parent[rb] = ra
	if uf.rank[ra] == uf.rank[rb] {
		uf.rank[ra]++
	}
	uf.Count--
	return true
}

func main() {
	uf := NewUnionFind(6)
	uf.Union(0, 1)
	uf.Union(2, 3)
	uf.Union(1, 3)
	fmt.Println(uf.Find(0) == uf.Find(2)) // true
	fmt.Println(uf.Find(0) == uf.Find(4)) // false
	fmt.Println(uf.Union(0, 3))           // false: would create a cycle
	fmt.Println(uf.Count)                 // 3  ({0,1,2,3}, {4}, {5})
}
#include <iostream>
#include <numeric>
#include <utility>
#include <vector>

class UnionFind {
    std::vector<int> parent, rank;

public:
    int count;  // number of disjoint sets

    explicit UnionFind(int n) : parent(n), rank(n, 0), count(n) {
        std::iota(parent.begin(), parent.end(), 0);
    }

    int find(int x) {
        int root = x;
        while (parent[root] != root) root = parent[root];
        while (parent[x] != root) {              // path compression
            int next = parent[x];
            parent[x] = root;
            x = next;
        }
        return root;
    }

    bool unite(int a, int b) {
        int ra = find(a), rb = find(b);
        if (ra == rb) return false;              // already connected
        if (rank[ra] < rank[rb]) std::swap(ra, rb);  // union by rank
        parent[rb] = ra;
        if (rank[ra] == rank[rb]) rank[ra]++;
        count--;
        return true;
    }
};

int main() {
    UnionFind uf(6);
    uf.unite(0, 1);
    uf.unite(2, 3);
    uf.unite(1, 3);
    std::cout << std::boolalpha;
    std::cout << (uf.find(0) == uf.find(2)) << '\n';  // true
    std::cout << (uf.find(0) == uf.find(4)) << '\n';  // false
    std::cout << uf.unite(0, 3) << '\n';              // false: would create a cycle
    std::cout << uf.count << '\n';                    // 3  ({0,1,2,3}, {4}, {5})
}

Practice on LeetCode

Classic problems that use this algorithm. Try them after working through the lab. Links open on LeetCode.

Complexity

With both optimizations, a sequence of m operations on n elements takes O(m · α(n)), where α is the inverse Ackermann function — at most 4 for any input that fits in the universe. Without them, a single find can cost O(n).

Typical uses

  • Kruskal’s minimum spanning tree: add an edge only if its ends are in different sets.
  • Connected components in a stream of edges, without storing the graph.
  • Detecting a cycle when adding edges to an undirected graph.
  • Grouping equivalent items: account merging, image segmentation, percolation.

Frequently asked questions

Everything you need to know about this tool and data security.

What exactly is rank?

An upper bound on the tree’s height. It only grows when two trees of equal rank are joined. Path compression may make the real height smaller, but rank is never decreased.

Can union-find split a set?

No. It only supports merging. Deletions or splits need different structures, such as link-cut trees, or rebuilding.

Union by size or union by rank?

Both give the same bounds. Size (number of elements) is handy when you also need the set sizes.

Is my data safe when using this tool?

Yes, 100% safe. This tool operates entirely inside your web browser using client-side JavaScript and WebAssembly. Your data never touches any external server.