Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Union-Find (Disjoint-Set Union): How It Works and When to Use It

Union-find tracks a changing partition with find and merge operations. Learn how its parent forest, path compression, and union heuristics work—and where DSU’s merge-only design falls short.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

As an Amazon Associate I earn from qualifying purchases.

The basic interface has three operations:

  • make_set(x) creates a set containing only x.
  • find_set(x) returns the representative of the set containing x.
  • union_sets(a, b) merges the sets containing a and b.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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
Sale
Introduction to Algorithms, fourth edition
  • 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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Path 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.

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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
Sale
Algorithm Design
  • Used Book in Good Condition
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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:

  1. Create one singleton set for each vertex with make_set(v).
  2. When an edge (u, v) is added, call find_set(u) and find_set(v).
  3. If the representatives differ, call union_sets(u, v) to join the components.
  4. 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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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

SaleBestseller No. 1
Introduction to Algorithms, fourth edition
Introduction to Algorithms, fourth edition
color: White; INTRODUCTION TO ALGORITHMS, FOURTH EDITION
$99.47
SaleBestseller No. 2
SaleBestseller No. 3
Bestseller No. 4
Algorithms
Algorithms
$95.41
SaleBestseller No. 5
Algorithm Design
Algorithm Design
Used Book in Good Condition
$223.83
  • 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.