Disjoint-set data structure

Also known as: union–find · merge–find set

On this page 7

A disjoint-set data structure maintains a collection of elements partitioned into non-overlapping groups and supports two operations: find, which reports the group an element belongs to, and union, which merges two groups into one. It is also known as union–find or a merge–find set, and among data structures it is the standard tool for tracking connectivity that only grows over time.

Programming with a disjoint set is attractive because, with two simple optimizations, each operation runs in amortized time that is practically constant. That efficiency makes it central to Kruskal’s minimum spanning tree algorithm, connected-component labeling, network connectivity checks and type unification in compilers.

How the disjoint-set forest represents groups

The usual implementation is a disjoint-set forest: every group is a tree, and every element stores a pointer to its parent. The element at the top of a tree, whose parent is itself, is the representative of the group. Two elements are in the same group exactly when following parent pointers from each leads to the same root.

The forest is normally stored as a plain integer array parent[], where index i holds the parent of element i, plus an auxiliary array for rank or size. This layout uses O(n) memory, has excellent cache behavior and needs no pointers or allocation after initialization.

The table below summarizes the three basic operations and what each one does to the forest.

OperationWhat it doesEffect on the forest
make-set(x)Creates a group containing only xx becomes its own root
find(x)Returns the representative of xWalks parent pointers to the root
union(x, y)Merges the groups of x and yOne root is attached under the other
Basic union–find operations

Union by rank and path compression

Without optimization, a sequence of unions can produce a tree shaped like a long chain, so find degrades to O(n). Two complementary techniques prevent this, and together they deliver the performance the structure is known for.

Union by rank or union by size always attaches the shallower or smaller tree beneath the root of the larger one, which keeps tree height at O(log n). Path compression makes every node visited during a find point directly at the root, flattening the tree for later queries. Lighter variants, path halving and path splitting, achieve the same bound in a single pass without recursion.

ImplementationWorst-case findAmortized cost
Naive linkingO(n)O(n)
Union by rank onlyO(log n)O(log n)
Path compression onlyO(n)O(log n)
Both combinedO(log n)O(α(n))
Effect of optimizations on cost per operation

Here α is the inverse Ackermann function, which grows so slowly that it is at most 4 for any input size that could exist in practice. Robert Tarjan proved this bound in 1975, and later work showed it is optimal for this class of algorithms, so union–find is effectively constant time without being strictly constant.

Disjoint sets compared with other connectivity methods

A disjoint-set data structure is the best choice when connections are only added, never removed, and queries arrive interleaved with updates. Other approaches answer similar questions but suit different workloads, so choosing among them depends on whether the graph is static, growing or changing in both directions.

MethodBest workloadMain limitation
Union–findIncremental edges, many queriesCannot delete edges or split groups
BFS or DFS traversalStatic graph, one-time labelingFull rescan after each change
Adjacency list with searchQueries about paths, not only groupsEach query costs O(V + E)
Dynamic connectivity treesInsertions and deletionsComplex, polylogarithmic cost
Hash map of set labelsVery small data setsMerging relabels many elements
Ways to answer connectivity questions

Unlike a general graph representation, a disjoint set stores no edges at all. It remembers only which elements are connected, not how, so it cannot reconstruct paths between members.

Typical applications in algorithms

Union–find appears wherever an algorithm must repeatedly merge groups and test membership. Its most famous role is in Kruskal’s algorithm, which sorts edges by weight and adds each one only if its endpoints lie in different components, using a find on each endpoint to decide.

ApplicationElementsWhat a union represents
Minimum spanning treeGraph verticesAccepting an edge into the tree
Image segmentationPixelsNeighboring pixels with similar values
Network connectivityHosts or routersA new link between devices
Type inferenceType variablesUnifying two types as equal
Maze generationGrid cellsRemoving a wall between cells
Account deduplicationUser recordsShared email or phone number
Common uses of the structure

Some applications extend each root with extra aggregated data, such as group size, minimum element or a parity bit. These augmented disjoint sets answer questions like the size of the largest cluster without any additional traversal.

Limitations and implementation mistakes

The structure is simple, yet several errors recur in production code and competitive programming alike. Most of them either break the complexity guarantee or produce subtly wrong groupings.

  • No support for deletion: splitting a group requires rebuilding or a persistent variant with rollback.
  • Comparing elements instead of roots: testing parent[x] == parent[y] gives wrong answers after unions.
  • Skipping union by rank: path compression alone still allows slow early operations.
  • Deep recursion in find: on large inputs, recursive compression can overflow the stack, so iterative versions are safer.
  • Path compression with rollback: undoable unions require union by rank without compression, accepting O(log n) finds.

A non-technical view

A disjoint-set data structure keeps track of who belongs to which group when groups only ever join together. Each group chooses one member as its leader, and every member knows how to reach that leader.

Imagine guests at a large party forming circles of friends. To learn whether two guests are in the same circle, ask each one for their circle’s leader and compare. When two circles meet, one leader agrees to follow the other, and the circles become one. Because guests remember the shortest way to their leader, answering the question stays almost instant even with millions of people.

A concrete example

An engineer at a telecommunications operator must monitor whether 20,000 network sites remain connected as new fiber links are commissioned throughout the year. The planning tool needs to answer, at any moment, whether two sites can already reach each other through installed links.

The engineer stores sites in a union–find structure with union by size and path halving. Each new link triggers one union, and each planning query triggers two finds. Augmented root data keeps the number of sites in each cluster, which the dashboard shows as a regional coverage figure.

Processing a full year of about 35,000 link events and several million queries takes under one second on a laptop. A previous version that ran a breadth-first search for every query had needed minutes, so the planning team now sees connectivity changes in real time as links come online.