🔗 Union-Find
Disjoint sets & path compression
Sets 8 / 8
Last op:
Setup
Operation
Stats
Disjoint sets
8
Operations
0
Max tree height
0
Status
Ready
parent[] array
Info & Theory

Union-Find (disjoint set union, DSU) keeps a collection of non-overlapping sets and answers, in near-constant time, whether two elements belong to the same set.

The two operations

  • find(x) follows parent pointers up to the root that represents x's set.
  • union(a, b) finds both roots and links one under the other, merging the two sets into one.

Union by rank

Each tree carries a rank — an upper bound on its height. We attach the smaller-rank root under the larger-rank root, so the tree stays shallow. On a tie, one root becomes the child and the survivor's rank rises by 1.

Path compression

During find, after reaching the root we re-point every node on the path directly at the root. The tree flattens, so later queries on those nodes are almost instant. This simulation highlights the traversed path, then redraws with the compressed pointers.

Why it is almost O(1)

With both tricks, m operations on n elements cost O(m·α(n)), where α is the inverse Ackermann function. Since α(n) ≤ 4 for any conceivable input, each operation is effectively constant time.

Where it is used

  • Counting connected components as edges are added.
  • Kruskal's minimum spanning tree (cycle detection).
  • Randomised maze generation via Kruskal's method.
  • Image segmentation, percolation, and dynamic connectivity.

Frequently asked questions

What is a union-find data structure?

Union-find, also called disjoint set union (DSU), maintains a collection of non-overlapping sets. It supports two core operations: find, which returns a representative (root) of the set containing an element, and union, which merges the two sets containing two elements. Two elements are in the same set exactly when they share the same root.

How is union-find represented internally?

Each set is stored as a rooted tree inside a single parent[] array. Every element points to its parent, and a root points to itself. The whole structure is therefore a forest of trees, one tree per disjoint set. To test connectivity you walk each element up to its root and compare the two roots.

What does union by rank do?

Union by rank attaches the shorter tree under the root of the taller tree, keeping trees shallow. Rank is an upper bound on a tree's height. When two roots have equal rank, one becomes the child of the other and the surviving root's rank increases by one. This stops the forest from degenerating into a long chain.

What is path compression?

Path compression is applied during find: after locating the root, every node visited on the way is re-pointed directly at that root. This flattens the tree so future queries on those nodes are almost instant. The simulation animates this by highlighting the traversed path, then redrawing with the compressed pointers.

Why is union-find almost O(1) per operation?

With both union by rank and path compression, a sequence of m operations on n elements runs in O(m·α(n)) time, where α is the inverse Ackermann function. α(n) grows so slowly that it is below 5 for any practical n, so each operation is effectively constant time even though it is not strictly O(1).

What is the inverse Ackermann function α(n)?

The Ackermann function grows astronomically fast, so its inverse α(n) grows astronomically slowly. For every input size that could fit in the observable universe, α(n) is at most 4. That is why the amortised cost of union-find with both optimisations is treated as essentially constant in practice.

How does union-find count connected components?

The number of disjoint sets equals the number of roots in the forest. Start with n singleton sets, so n components. Each successful union of two different sets reduces the component count by exactly one. This makes union-find an efficient way to track connectivity in a graph as edges are added.

How is union-find used in Kruskal's MST algorithm?

Kruskal's minimum spanning tree algorithm sorts edges by weight and adds each edge only if its endpoints are in different sets, which is checked with find. Adding the edge performs a union. Union-find makes this cycle detection nearly constant time, which is why Kruskal runs in O(E log E) dominated by the sort.

Can union-find help generate mazes?

Yes. A randomised version of Kruskal's algorithm builds perfect mazes: start with every cell as its own set and walls everywhere, then repeatedly knock down a random wall only if the two cells it separates are in different sets, unioning them. This guarantees a fully connected maze with no loops.

What happens if you union two elements already in the same set?

If find(a) and find(b) return the same root, the elements are already connected, so union does nothing structurally and the component count is unchanged. A robust implementation detects this early and skips the rank update, avoiding redundant work while keeping the forest correct.

About Union-Find (Disjoint Sets)

Written by MySimulator Team · Reviewed by MySimulator Editorial Review

Last updated: 5 July 2026

The Union-Find data structure, also called Disjoint Set Union (DSU), efficiently maintains a partition of n elements into disjoint sets and supports two operations: Union (merge two sets) and Find (identify which set an element belongs to). With two optimisations — union by rank (or size) and path compression — both operations achieve an amortised time complexity of O(α(n)) per call, where α is the extremely slowly growing inverse Ackermann function. For all practical n, α(n) ≤ 4, making Union-Find essentially constant time in practice.

The simulation lets you add edges to a graph one at a time and watch connected components merge in real time. You can toggle path compression on and off to compare tree heights, observe how union by rank keeps trees shallow, and count the total number of pointer updates required to process a sequence of Union operations.

Frequently Asked Questions

What does path compression do?

During a Find operation, path compression makes every node on the path from element x to the root point directly to the root. This flattens the tree so future Find calls for the same elements are O(1). Without path compression but with union by rank, Find is O(log n); together they achieve O(α(n)) amortised, proved by Tarjan and van Leeuwen in 1984.

What is union by rank (union by size)?

Union by rank always attaches the root of the shallower tree under the root of the taller tree, keeping the maximum tree height at O(log n) without path compression. Union by size is a variant that tracks the number of elements rather than height; both achieve the same asymptotic bound. Without either heuristic, a sequence of n Unions can produce a chain of height n, degrading Find to O(n).

What is the inverse Ackermann function and why is it relevant?

The Ackermann function A(k, k) grows faster than any primitive recursive function; its inverse α(n) is therefore astronomically small. For n = 2^65536, α(n) = 5. This means that for any input size encountered in practice, the amortised cost of Union and Find is less than 5 operations — effectively constant. The bound was proved by Tarjan in 1975.

How is Union-Find used in Kruskal's MST algorithm?

Kruskal's algorithm builds a minimum spanning tree by sorting edges by weight and adding each edge if it connects two different components (detected by Find) and then merging those components (Union). With Union-Find, each of the O(E) edge checks costs O(α(V)), giving an overall complexity of O(E log E) dominated by the initial sort.

Can Union-Find detect cycles in a graph?

Yes. Before adding an edge (u, v) to a graph, call Find(u) and Find(v). If they return the same root, u and v are already in the same component and adding the edge would create a cycle. This is exactly how Kruskal's algorithm avoids cycles. The check is O(α(n)) amortised, far cheaper than a DFS cycle check on the full graph.

What are other applications of Union-Find?

Union-Find is used in network connectivity queries, image segmentation (merging pixels of the same region), percolation simulation (used to study phase transitions in physics), compiler implementation (equivalence class merging), and in online algorithms for dynamic connectivity. It is also a key primitive in social network analysis for computing connected components.

Is there a version of Union-Find that supports splitting sets?

No — standard Union-Find only supports merging, not splitting. This is a fundamental limitation: efficient "link" and "find" operations with "cut" (splitting) require more complex structures such as link-cut trees (also by Tarjan), which support all three operations in O(log n) amortised time.

What is the difference between union by rank and union by size?

Union by rank tracks an upper bound on the height of each tree. Union by size tracks the exact number of nodes. Both keep trees shallow and achieve the same O(α(n)) amortised bound with path compression. Union by size is slightly easier to implement correctly (rank can become an overestimate after path compression), but both are standard. Most competitive-programming implementations use union by size.

How does Union-Find handle the percolation problem?

In percolation, an n×n grid of sites is opened randomly; the question is whether a path of open sites connects the top row to the bottom. Union-Find is used with two virtual nodes (top and bottom) connected to all open sites in the top and bottom rows respectively. A connection from top to bottom (same root) signals percolation. Monte Carlo simulation shows the threshold is approximately 0.593 for a square grid.