TL;DR
A disjoint-set structure holds a collection of items split into groups, where no item is in two groups. It supports two operations: find, which tells you which group an item belongs to, and union, which merges two groups into one. With two simple tricks, each operation takes almost constant time on average, which makes the structure one of the most useful small tools in algorithms.
Builds on: Tree (Graph Theory), Recursion · Leads to: Minimum Spanning Tree (Kruskal's algorithm uses this structure to avoid cycles)
Where it's used
Detecting cycles while building a network. When you add a cable between two offices, you need to know whether they are already connected. If they are, the new cable would create a loop. Kruskal's algorithm for the cheapest network does exactly this check for every candidate cable, and it uses this structure to answer it.
Grouping pixels or regions. Image processing programs label connected blobs of pixels, and this structure is one way to do it (a breadth-first search is another). Each pixel starts in its own group, and touching pixels of the same colour are merged. Scanning a large image this way needs millions of find and union calls.
Tracking friendships or accounts. A system that merges accounts when a user links two of them, or a social app that asks whether two people are in the same friend cluster, can keep groups in this structure and answer each query without rebuilding the groups. Each account is stored as an item, usually found by its id in a hash table.
How it works
Think of each group as a family tree. Every item has a parent pointer. An item whose parent is itself is the root of its group, and the root serves as the group's name.
-
Start with singletons. Create
nitems, and set each item's parent to itself. Now there arengroups, each with one item and one root. -
find(x)walks up. Starting atx, follow parent pointers until you reach an item whose parent is itself. That item is the root, and it names the group. Example: ifxhas parenty, andyis its own parent, thenfind(x)returnsy. -
union(x, y)finds two roots. Callfind(x)andfind(y). If they are equal,xandyare already in the same group, and nothing changes. -
union(x, y)links one root under the other. If the roots differ, make one root the parent of the other. Now there is one group with one root. Two groups have become one. -
Pick the parent wisely. Making a root point to the other can build a long chain, and then
findwould be slow. The fix is union by size: attach the smaller tree under the root of the larger one. The tree height then grows only when two trees of equal size merge, so it grows slowly. -
Shorten paths as you go. When
findwalks up a path, it can point every visited item directly at the root. This is path compression. The nextfindon any of those items is one step long.
With both tricks, a sequence of m operations on n items takes time close to m times a constant. The exact bound involves the inverse Ackermann function, which grows so slowly that it is at most 4 for any input that fits in a computer's memory.
The figure shows a group of four items, 1, 2, 3 and 5, with root 1. Item 3 was attached under root 1, and item 5 was attached under item 3 before compression. After find(5), item 5 points straight at the root.
flowchart TD
subgraph before[Before find 5]
R1((1)) --> A1((2))
R1 --> B1((3))
B1 --> C1((5))
end
subgraph after[After find 5 with path compression]
R2((1)) --> A2((2))
R2 --> B2((3))
R2 --> C2((5))
end
The math
The structure is a set of rooted trees, one per group. Write p(x) for the parent of item x. A root r has p(r) = r. Write find(x) for the root reached by following parents from x.
A family of disjoint sets S₁, S₂, …, Sₖ partitions a universe of n items: every item is in exactly one set. Each set is represented by one of its members, its root. The two operations are find(x), which returns the root of the set containing x, and union(x, y), which replaces the two sets containing x and y by their union.
Step 3 in symbols: the cycle test
Adding an edge between vertices u and v to a forest creates a cycle exactly when u and v are already in the same tree. In terms of the structure:
This is the test Kruskal's algorithm uses.
Step 5 in symbols: union by size
Let size(r) be the number of items in the tree rooted at r. When uniting roots r and s with size(r) ≥ size(s), set p(s) = r and size(r) = size(r) + size(s). The depth of any item grows by one only when its tree is attached under a tree of at least the same size. Each time an item's depth increases, the size of its group at least doubles. A group of size n therefore has depth at most log₂ n. This is the reason the height stays logarithmic, using the Logarithm function.
Step 6 in symbols: path compression
When find(x) visits the path x = v₀, v₁, …, vₜ = root, it sets p(vᵢ) = root for every i. The cost of one find is proportional to the length of the path it walks, and compression shortens every path it touches. Combined with union by size, the amortized cost per operation is O(α(n)), where α is the inverse Ackermann function. For any practical n, α(n) ≤ 4.
Worked examples
Items a, b, c, d. Start with four groups: {a}, {b}, {c}, {d}.
- union(a, b). find(a) is a and find(b) is b. They differ, so set p(b) = a. Groups: {a, b}, {c}, {d}.
- union(c, d). Set p(d) = c. Groups: {a, b}, {c, d}.
- find(b). Follow b to a. Since p(a) = a, the root is a.
- find(c) is c and find(a) is a. They differ, so the items a and c are in different groups.
- union(b, c). find(b) is a and find(c) is c. Set p(c) = a. Groups: {a, b, c, d}.
- Check: find(d) follows d to c, then to a. The root is a, the same as find(b). All four items are in one group.
Items 1 to 6, all singletons. Apply the operations in order and track parent pointers and sizes.
- union(1, 2). Both roots have size 1. Attach 2 under 1. Now p(2) = 1 and size(1) = 2.
- union(3, 4). Attach 4 under 3. Now p(4) = 3 and size(3) = 2.
- union(1, 3). Roots are 1 and 3, both of size 2. Attach 3 under 1. Now p(3) = 1 and size(1) = 4. The tree of 1 is {1, 2, 3, 4}, and 4 is at depth 2.
- find(4). Visit 4, then 3, then 1. The root is 1. Compression sets p(4) = 1 and p(3) = 1 (3 was already a child of 1).
- After compression, 4 is directly under 1. Calling find(4) again visits only 4 and 1.
- union(5, 6). Attach 6 under 5. Now there are two groups: {1, 2, 3, 4} and {5, 6}.
- Check the sizes: 4 + 2 = 6 items, which equals the number of items. No item has been lost.
Five offices A, B, C, D, E. Cables with costs: AB 1, BC 2, AC 3, CD 4, DE 5, BE 6. Kruskal's algorithm takes cables in increasing cost order and keeps a cable only if it joins two different groups.
- Start with five groups: {A}, {B}, {C}, {D}, {E}.
- Cable AB, cost 1. find(A) is A, find(B) is B. Different, so keep it. Groups: {A, B}, {C}, {D}, {E}. Total cost 1.
- Cable BC, cost 2. find(B) is A (the root of {A, B}) and find(C) is C. Different, so keep it. Groups: {A, B, C}, {D}, {E}. Total cost 3.
- Cable AC, cost 3. find(A) and find(C) are both A now. Same group, so this cable would make a cycle. Discard it.
- Cable CD, cost 4. find(C) is A, find(D) is D. Different, so keep it. Groups: {A, B, C, D}, {E}. Total cost 7.
- Cable DE, cost 5. Different groups, keep it. Groups: {A, B, C, D, E}. Total cost 12.
- Cable BE, cost 6. Same group, discard.
- Check: four cables were kept, which equals 5 − 1, the number of edges in a tree on five vertices. The total cost is 1 + 2 + 4 + 5 = 12.
- Try it: suppose AC costs 1.5 instead of 3. Which cables are kept, and what is the total? Answer: The sorted order is AB 1, AC 1.5, BC 2, CD 4, DE 5, BE 6. Keep AB. Keep AC, since A is in {A, B} and C is alone. Discard BC, since B and C are now both in the group with root A. Keep CD and DE. Discard BE. Kept cables: AB, AC, CD, DE, with total 1 + 1.5 + 4 + 5 = 11.5.
Common mistakes and tradeoffs
It is tempting to think that union must rebuild the groups, since the groups are changed. In fact it only changes one parent pointer, between two roots. Nothing else moves, which is why the operation is fast.
It is tempting to think that path compression alone is enough. In fact compression without union by size still gives a good amortized bound, but the tree can be tall for a single find before compression helps. Using both gives the best bound and keeps the worst single operation short. Union by size is cheap to store, one number per root.
It is tempting to think that the structure can split a group. In fact it cannot. It supports only merging. If you need to remove an item from a group or split a group, use a different structure, such as a balanced tree or a dynamic connectivity structure.
Use this structure when the groups only grow and you need fast membership tests, as in Kruskal's algorithm or in counting connected regions. Do not use it when you need to know the actual members of a group quickly, since find returns only the root. Keeping an array of members per root is possible but adds work during union.
History
In 1964 Bernard Galler and Michael Fisher described an efficient way to handle equivalence classes in a computer program, using trees with parent pointers and merging by size. Their method made it practical to track groups in the memory of the machines of the day. The path compression trick was added later and the analysis was completed in the 1970s, when Robert Tarjan showed that the combined method runs in time governed by the inverse Ackermann function. Tarjan's result made the structure a standard tool in graph algorithms, including Kruskal's method for finding a minimum spanning tree, which was published in 1956 by Joseph Kruskal.
Recap
- A disjoint-set structure stores groups as rooted trees, one tree per group, with the root as the group's name.
find(x)follows parent pointers to the root.union(x, y)links the two roots, and does nothing if they are equal.- Union by size keeps trees shallow. Path compression shortens the paths that
findwalks. - With both, a long sequence of operations costs almost a constant per operation on average.
- Kruskal's algorithm uses this structure to check whether a new edge would close a cycle in a tree. Read Minimum Spanning Tree next to see the whole algorithm.
Check yourself
QuestionRecall: what does find(x) return, and how do you know an item is a root?Show answer
find(x) returns the root of the group containing x, found by following parent pointers until an item is reached whose parent is itself. A root is an item whose parent pointer points to itself.
QuestionComputation: six items start as singletons. Three unions each merge two different groups. How many groups remain?Show answer
Each successful union reduces the number of groups by one. Starting from six groups, three successful unions leave 6 − 3 = 3 groups.
QuestionWhy does union by size keep the trees shallow?Show answer
An item's depth increases only when its tree is attached under a tree at least as large as its own. Each such increase at least doubles the size of the group that item belongs to. A group of n items can therefore be doubled at most log₂ n times, so depth is at most log₂ n.
QuestionApplied: in Kruskal's algorithm, a candidate cable joins office X and office Y, and find(X) and find(Y) return the same root. What should the algorithm do with the cable, and why?Show answer
It should discard the cable. Equal roots mean X and Y are already connected through kept cables, so keeping this cable would create a cycle, and a minimum spanning tree has no cycle.
Sources
- Disjoint-set data structure, Wikipedia: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
- Kruskal's algorithm, Wikipedia: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm