Union-find, also called disjoint-set union (DSU), tracks a collection of non-overlapping sets as they are merged. It answers whether two elements are in the same set and combines sets efficiently. It is especially useful for incremental connectivity in an undirected graph, but it does not support arbitrary splits or preserve a directly enumerable list of every set’s members.
What union-find tracks
A disjoint set is a group whose members do not also belong to another group in the same collection. Together, the groups form a partition of the elements. Union-find stores that changing partition in a compact form: it can identify which group contains an element and merge two groups, without storing a full list of every group’s members as its primary representation.
| # | Preview | Product | Price | |
|---|---|---|---|---|
| 1 |
|
Introduction to Algorithms, fourth edition | $99.47 | Buy on Amazon |
| 2 |
|
Algorithms (4th Edition) | $68.77 | Buy on Amazon |
| 3 |
|
Introduction to Algorithms, 3rd Edition | $90.43 | Buy on Amazon |
| 4 |
|
Algorithms | $95.41 | Buy on Amazon |
| 5 |
|
Algorithm Design | $223.83 | Buy on Amazon |
As an Amazon Associate I earn from qualifying purchases.
The basic interface has three operations:
make_set(x)creates a set containing onlyx.find_set(x)returns the representative of the set containingx.union_sets(a, b)merges the sets containingaandb.
Two elements belong to the same set when their representatives match. A representative is an internal choice, not a permanent or meaningful group label: a successful merge can change which root represents the combined set. If an application needs stable external labels, it should store them separately. See the CP-Algorithms explanation of disjoint-set union and Princeton’s UF API.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
How the parent forest represents sets
Each element starts as its own parent. A set is represented by a rooted tree: following parent pointers eventually reaches the root, and that root is the set’s representative. The collection of these trees is called a forest.
#1 Best Overall
- color: White
- INTRODUCTION TO ALGORITHMS, FOURTH EDITION
To merge two sets, first find their roots. If the roots are the same, the elements were already together and no change is needed. Otherwise, make one root a child of the other. Only roots should be joined; changing the parent of a non-root as if it were a set representative can corrupt the structure.
Why naive merging can be slow
If each merge attaches one root to the other without regard to tree shape, repeated choices can create a long chain. A later find may have to follow many parent links before reaching the root.
Rank #2
Union by size or rank
Union by size stores the number of elements in each tree and attaches the smaller tree’s root below the larger tree’s root. Union by rank stores a rank used as an upper bound on height: attach the lower-rank root under the higher-rank root, and increase the surviving root’s rank by one when the ranks tie. These rules keep trees from becoming unnecessarily tall.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPath compression
During find_set(x), path compression updates parent pointers along the route to the root so later lookups can reach it more directly. A common implementation points each visited node straight to the root. Compression changes the forest’s shape, but not the set membership it represents.
Rank #3
Time complexity: nearly constant amortized cost
With path compression and union by size or rank, a sequence of m operations over n elements takes O(m α(n)) time, or O(α(n)) amortized per operation. Here, α(n) is the inverse Ackermann function, which grows so slowly that the bound is effectively constant for practical input sizes. This is a bound on the sequence as a whole; it does not promise that every individual call has constant worst-case cost. The CP-Algorithms DSU reference gives the amortized bound.
Bounds can also depend on the implementation and on which kind of cost is being described. Princeton’s UF API documentation states O(log n) worst-case time for an individual find or union in its implementation, and O(m α(n)) for an intermixed sequence. These statements are compatible: an individual operation’s worst-case bound and the amortized cost across a sequence answer different questions.
Rank #4
How common union-find variants compare
Implementations trade off the cost of finding roots, merging sets, and maintaining extra information. The labels below refer to the variants presented in Princeton’s union-find case study.
Recommended Free Tools
| Variant | Representation or heuristic | Main trade-off |
|---|---|---|
| Quick-find | Stores a component identifier for each element. | Membership checks are direct, but merging may require updating many identifiers. |
| Quick-union | Uses parent pointers to form trees. | Merging roots is simple, but unbalanced trees can make finds slow. |
| Weighted quick-union | Attaches the smaller tree beneath the larger, using size or rank information. | Tree height is controlled, but paths may still be longer than with compression. |
| Weighted quick-union with path compression | Combines size or rank weighting with find-time parent updates. | Provides the near-constant amortized sequence cost commonly associated with DSU. |
For a practical implementation, weighted union plus path compression is a common default. The right comparison depends on whether the application cares about an individual operation’s worst case, amortized sequence performance, metadata overhead, or operations beyond merging.
Best Value
Using union-find for graph connectivity
For an undirected graph whose edges are added over time, DSU can maintain connected components without rerunning a full graph traversal after every addition:
- Create one singleton set for each vertex with
make_set(v). - When an edge
(u, v)is added, callfind_set(u)andfind_set(v). - If the representatives differ, call
union_sets(u, v)to join the components. - To test whether two vertices are connected, compare their representatives.
This works because adding an edge can join two previously separate components, but cannot split one. The CP-Algorithms applications section also describes connected-component labeling in images and specialized uses such as certain range updates processed in reverse order.
Why Kruskal’s algorithm uses DSU
Kruskal’s minimum-spanning-tree algorithm considers edges in sorted order. For each edge, it checks whether the endpoints have the same representative. If they do, adding the edge would close a cycle in the selected forest, so the algorithm skips it. If the representatives differ, the edge joins two components and DSU merges them. This makes the component check and merge efficient within the algorithm.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Where ordinary DSU stops being the right tool
Standard union-find supports merging classes; it has no inverse operation for separating one class into two. In a graph, deleting an edge may or may not disconnect its endpoints, and if it does, DSU cannot determine the newly separated components from its merge-only forest. The forest records component membership, not enough of the original graph to reconstruct its edges.
Quick Recap
- For a static graph, depth-first search or breadth-first search can label its connected components.
- For a workload that includes edge deletions or fully dynamic connectivity, use a method designed for those updates; offline techniques and dynamic-connectivity data structures are separate approaches.
- If an application needs to enumerate every member of a component or attach application-specific metadata to components, maintain that information separately. The ordinary parent forest is designed for representative lookup and merging, not as a member list.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




