Disjoint Sets and Union-Find
A disjoint set, or union-find, keeps elements in non-overlapping groups and answers one question fast: are these two in the same group? Each group is a tree in a parent array, kept flat by union by rank and path compression.
The Problem It Solves
A disjoint set, also called union-find or disjoint set union (DSU), keeps a collection of elements split into groups that do not overlap. Every element is in exactly one group. The disjoint set data structure supports two operations: find which group an element is in, and union two groups into one.
Connectivity is the question it answers. If cables are added to a network one at a time and you must say after each one whether two machines can reach each other, a fresh BFS costs O(V + E) per question. Union-find keeps the groups up to date as edges arrive and answers in near-constant time.
find(x) returns the group's representative, one element chosen to name the group. Two elements are connected exactly when find(x) == find(y). union(x, y) merges the two groups that contain x and y.
The price is a narrow interface. You cannot list a group's members cheaply, and you cannot split a group at all. Merging is the only change it supports.
- Connected means
find(x) == find(y), neverx == y - No split or delete: groups only ever merge
Sets as Trees in One Array
Each group is a tree stored in a single array: parent[i] is the element above i. An element that is its own parent is a root, and the root is the group's representative. At the start parent[i] = i for every i, so there are n one-element groups.
find(x) follows parent links until it reaches a root. Its cost is the number of hops, the depth of x in its tree.
union(x, y) finds both roots and, if they differ, points one root at the other. That single write merges two whole trees, because everything below a root comes with it. If the roots are equal, x and y were already together and nothing changes.
Linking without care can build a chain. Always hanging the old root under the next element, as in union(0, 1), union(1, 2), union(2, 3) and so on, gives a tree n − 1 levels deep, and find becomes O(n). The two optimisations below exist to stop that.
- Link the roots:
parent[find(x)] = find(y); writingparent[x] = ymoves one element and splits its set
Union by Rank and Path Compression
- Find both roots,
ra = find(a)andrb = find(b); stop if they are equal - Hang the root with the smaller rank under the root with the larger rank
- If the ranks were equal, pick either as the new root and add 1 to its rank
Union by rank decides which root goes on top. Each root keeps a rank, an upper bound on its tree's height. Hanging a shorter tree under a taller one leaves the height unchanged; only a tie makes the tree one level taller. So a tree of rank r has at least 2^r elements, and the height never passes log₂ n.
Union by size is the common alternative: hang the tree with fewer elements under the larger one. It gives the same O(log n) bound, and the sizes answer 'how big is this group?' for free.
Path compression makes find tidy up after itself. While walking from x to the root, it points every element on that path straight at the root. In the recursive version that is one line, parent[x] = find(parent[x]). The next find on any of those elements takes one hop.
Ranks are not updated by path compression, so after a while a rank can overstate the real height. That is fine: rank only needs to be an upper bound, and it is only read at roots.
With both optimisations, a sequence of m operations on n elements costs O(m · α(n)), where α is the inverse Ackermann function. It grows so slowly that it is at most 4 for any realistic n, so in practice each operation is constant time.
Recursive find can overflow the stack on a long chain before compression has flattened it. An iterative find avoids that: walk up once to find the root, then walk again repointing each element; or use path halving, parent[x] = parent[parent[x]] on every step.
| Optimisations | find and union | Why |
|---|---|---|
| Neither | O(n) | Unions can build a chain |
| Union by rank only | O(log n) | Height grows only on a tie |
| Path compression only | O(log n) amortised | Each find flattens its path |
| Both | O(α(n)) | α(n) ≤ 4 for any n that fits in memory |
- Rank changes only at a root, and only on a tie
- Use path halving or a two-pass find when trees can start very deep
Terms, operations, and practical uses
Core vocabulary
- Disjoint SetsA collection of sets where no element belongs to more than one set.
- Representative (Root)The unique element used to identify a specific set. If two elements have the same root, they are in the same set.
- Connected ComponentA maximal set of vertices in a graph that are all reachable from one another.
Operations
- FindAn operation that returns the root representative of the set containing a given element.
- UnionAn operation that merges two sets by making the root of one set point to the root of the other.
- InitializationStarting state where every element is in its own set (i.e., its parent is itself).
Optimizations
- Path CompressionAn optimization in
Findthat makes every visited node point directly to the root, flattening the tree. - Union by RankAn optimization in
Unionthat always attaches the shorter tree under the root of the taller tree to keep the tree shallow. - Inverse Ackermann α(N)The resulting amortized time complexity, which is so slow-growing it is effectively O(1) for any practical input size.
Code in Python, C++ and Java
parent = list(range(6)) # every element is its own root
rank = [0] * 6 # tree height, used to keep unions shallow
def find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False # already together: this edge is a cycle
if rank[ra] < rank[rb]:
ra, rb = rb, ra # attach the shorter tree
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return True
union(0, 1)
union(2, 3)
union(1, 3)
groups = {}
for i in range(6):
groups.setdefault(find(i), []).append(i)
first, *rest = groups.values()
fmt = lambda g: '{ ' + ', '.join(map(str, g)) + ' }'
print('Root of 0 is', find(0), '— one set ' + fmt(first) + ', plus ' + ' and '.join(map(fmt, rest)))#include <iostream>
#include <map>
#include <numeric>
#include <vector>
using namespace std;
vector<int> parent(6);
vector<int> rnk(6, 0); // tree height, used to keep unions shallow
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]); // path compression
return parent[x];
}
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already together: a cycle
if (rnk[ra] < rnk[rb]) swap(ra, rb); // attach the shorter tree
parent[rb] = ra;
if (rnk[ra] == rnk[rb]) rnk[ra]++;
return true;
}
int main() {
iota(parent.begin(), parent.end(), 0); // every element is its own root
unite(0, 1);
unite(2, 3);
unite(1, 3);
map<int, vector<int>> groups;
for (int i = 0; i < 6; i++) groups[find(i)].push_back(i);
cout << "Root of 0 is " << find(0);
bool first = true;
for (auto& g : groups) {
cout << (first ? " — one set { " : " { ");
for (size_t i = 0; i < g.second.size(); i++) {
if (i) cout << ", ";
cout << g.second[i];
}
cout << " }";
if(first) {
cout << ", plus";
first = false;
}
else if (g.first != groups.rbegin()->first) cout << " and";
}
cout << '\n';
}import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
class Main {
static int[] parent = new int[6];
static int[] rank = new int[6]; // tree height, used to keep unions shallow
static int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]); // path compression
return parent[x];
}
static boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already together: a cycle
if(rank[ra] < rank[rb]) {
int t = ra;
ra = rb;
rb = t;
}
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
return true;
}
public static void main(String[] args) {
for (int i = 0; i < 6; i++) parent[i] = i; // every element is its own root
union(0, 1);
union(2, 3);
union(1, 3);
Map<Integer, List<Integer>> groups = new LinkedHashMap<>();
for (int i = 0; i < 6; i++) groups.computeIfAbsent(find(i), k -> new ArrayList<>()).add(i);
StringBuilder sb = new StringBuilder("Root of 0 is " + find(0));
boolean first = true;
int seen = 0;
for (List<Integer> g : groups.values()) {
seen++;
sb.append(first ? " — one set { " : " { ");
for (int i = 0; i < g.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(g.get(i));
}
sb.append(" }");
if(first) {
sb.append(", plus");
first = false;
}
else if (seen < groups.size()) sb.append(" and");
}
System.out.println(sb);
}
}Step through it
Running on union(0,1), union(2,3), union(1,3), find(0), then find(3) and more unions
Where It Is Used, and What Goes Wrong
Kruskal's algorithm for a minimum spanning tree takes edges from lightest to heaviest and keeps an edge only if its ends have different roots. Union-find makes that check cheap.
Connected components of an undirected graph fall out directly: union the ends of every edge, then count the distinct roots. Undirected cycle detection is the same loop: an edge whose ends already share a root closes a cycle. Grid problems such as counting islands use the same idea with edges between neighbouring cells.
Comparing elements instead of roots. x == y asks whether they are the same element. Every connectivity test must go through find.
Writing parent[x] = y. This moves one element out of its tree instead of merging two sets. Its old set mates no longer share a root with it, and the partition is silently wrong.
Updating rank on non-roots. Rank is read only at roots. Changing it anywhere else gives wrong balancing choices; answers stay correct but the trees get taller.
Expecting delete or split. Path compression has already thrown away the shape the unions built, so there is no way back. If a problem removes edges, process the operations in reverse so removals become unions.
- Practice: Number of Provinces, Redundant Connection, Accounts Merge