Quick reference
Union-find (also called a disjoint set union, or DSU) is a data structure that keeps track of items split into non-overlapping groups. It does two things quickly: find tells you which group an item is in, and union merges two groups into one.
How it works:
- Each group is a tree. Every item points to a parent, and the item at the top of the tree (the root) names the group.
- find(x) follows parent pointers up to the root. Two items are in the same group if they have the same root.
- union(a, b) finds both roots and points one at the other.
Two tricks keep it fast:
- Path compression: after a find, point every item it passed straight at the root.
- Union by size (or by rank): always put the smaller tree under the bigger one.
Cost:
- With both tricks, find and union take O(α(n)) amortized time, where α is the inverse Ackermann function. That's at most 4 for any input that could fit in memory, so it's nearly constant, but it isn't O(1). Space is O(n).
How Union-Find Works
Say six bakeries, numbered 0 through 5, start out as independent businesses. Over time, some of them merge into bigger companies, and we want to answer questions like "are bakeries 1 and 5 owned by the same company now?"
Union-find stores who reports to whom in a
array called parent.
Think of parent[x] as the bakery that bakery
x reports to:
-
At the start, every bakery reports to itself:
parent[x] == x. A bakery that reports to itself is a root, the headquarters of its company. - find(x) follows the chain of "reports to" links from x until it reaches a headquarters, and returns it. Two bakeries are in the same company exactly when they have the same headquarters.
- union(a, b) finds the headquarters of a and of b. If they're different, it makes one headquarters report to the other, which merges the two companies.
That's all it takes to be correct. But if we link roots carelessly, a company can turn into one long chain, like 5 → 4 → 3 → 2 → 1 → 0, and every find from the bottom has to walk the whole thing: O(n) time. Two tricks prevent that.
Union by size (or rank)
When merging, make the smaller group's root report to the bigger group's root, and keep a count of each group's size at its root. An item only gets one step farther from its root when its group joins a group at least as big, so its group at least doubles in size every time that happens. A group can't double more than log2 n times, so no tree ever gets taller than log2 n, and find takes O(log n) time even without the second trick.
Union by rank does the same thing with a different number. Each root keeps a rank, an upper bound on its tree's height. The root with the lower rank goes under the one with the higher rank, and if they're tied, either one can go on top and its rank goes up by 1. Both give the same guarantees. Size is handy when you also want to know how big each group is.
Path compression
Once find(x) has walked up to the root, it already
knows the answer for every item it passed along the way. So it
makes a second pass and points each of them directly
at the root. The next find on any of those items takes one step.
Trees get flatter every time you use them.
Union-Find Example, Step by Step
Here's the parent array
for our six bakeries as the mergers happen. We use union by size,
and when two groups are the same size, the second root goes under
the first.
| Step | Operation | What happens |
parent (items 0 to 5) |
Groups |
|---|---|---|---|---|
| Start | Every item is its own root. | [0, 1, 2, 3, 4, 5] | {0} {1} {2} {3} {4} {5} | |
| 1 | union(0, 1) | Roots 0 and 1 have the same size, so 1 goes under 0. | [0, 0, 2, 3, 4, 5] | {0, 1} {2} {3} {4} {5} |
| 2 | union(2, 3) | Same size, so 3 goes under 2. | [0, 0, 2, 2, 4, 5] | {0, 1} {2, 3} {4} {5} |
| 3 | union(1, 3) | find(1) is 0 and find(3) is 2. Both groups have 2 items, so root 2 goes under root 0. | [0, 0, 0, 2, 4, 5] | {0, 1, 2, 3} {4} {5} |
| 4 | union(4, 5) | Same size, so 5 goes under 4. | [0, 0, 0, 2, 4, 4] | {0, 1, 2, 3} {4, 5} |
| 5 | union(5, 3) | find(5) is 4. find(3) walks 3 → 2 → 0, and path compression points 3 straight at 0. Root 4's group (2 items) is smaller than root 0's (4 items), so 4 goes under 0. | [0, 0, 0, 0, 0, 4] | {0, 1, 2, 3, 4, 5} |
| 6 | find(5) | Walks 5 → 4 → 0, returns 0, and points 5 straight at 0. | [0, 0, 0, 0, 0, 0] | {0, 1, 2, 3, 4, 5} |
After step 4, asking whether bakeries 1 and 5 are connected means comparing find(1), which is 0, with find(5), which is 4. They're different, so the answer is no. After step 5, both finds return 0.
Notice that parent[3] was 2 after step 3, even though
3's group was named by root 0. Only find tells you an
item's group. A parent entry on its own doesn't.
Union-Find Implementation
Here's union-find with path compression and union by size. Items are numbered 0 to n - 1. We also keep a count of how many groups there are, which goes down by one every time a union actually merges two groups. The example at the bottom runs the same steps as the table above:
union returns whether it merged two different groups.
That one bit of information is what powers cycle detection and
Kruskal's algorithm below.
If your items aren't numbered 0 to n - 1 (they're
strings, say, or grid coordinates), either give each one a number
with a hash map first, or store
parent and size in
hash maps and add each item the first time
you see it.
Union-Find Time and Space Complexity
How fast union-find is depends on which tricks you use. Here n is the number of items, and "amortized" means averaged over a long sequence of operations:
| Version | find and union, amortized | One find, worst case |
|---|---|---|
| Neither trick | O(n) | O(n) |
| Union by size or rank only | O(log n) | O(log n) |
| Path compression only | O(log n) | O(n) |
| Both | O(α(n)) | O(log n) |
Setting up the structure takes O(n)
time, and it uses O(n) space for the
parent and size
arrays.
What's the inverse Ackermann function?
The Ackermann function is a function that grows absurdly fast, much faster than 2^n or even towers of powers of 2. Its inverse, written α(n), grows just as absurdly slowly. It's at most 4 for every n up to a number far bigger than the number of atoms in the observable universe.
So with both tricks, any long sequence of finds and unions costs at most a small constant number of steps each, on average. Two things keep it from being a true O(1):
- α(n) does keep growing as n grows. It just grows so slowly that you'll never see it.
- It's an amortized bound. A single find can still take O(log n) steps. It's the average over many operations that's nearly constant, because each slow find flattens the tree for the finds after it.
In an interview, "O(α(n)) amortized, which is nearly constant" is the precise answer. If you only implement one trick, the safe answer is O(log n).
What Union-Find Is Used For
Connected components and cycle detection
To count the connected components in an undirected graph, start with every node in its own group and union the two ends of every edge. The number of groups left is the number of components.
An undirected graph has a cycle exactly when some edge connects two
nodes that are already connected. So if
union ever returns false, that edge closes a loop:
Both take O(V + E · α(V)) time for V nodes and E edges, and they never need to build an adjacency list.
Kruskal's algorithm
Kruskal's algorithm
finds a
minimum spanning tree
by going through the edges from cheapest to most expensive and
keeping each edge that doesn't create a cycle. That's exactly the
check above: if union(a, b) returns true, the edge
joins two different trees, so keep it. If it returns false, skip it.
Sorting the edges takes O(E log E)
time, and all the unions and finds together are nearly linear, so
the sort is the slow part.
Grouping equivalent items
Any time a problem says "if A matches B and B matches C, then A
matches C," union-find can build the groups. For example, in
"accounts merge," each account is a list of email addresses, and two
accounts belong to the same person if they share any address. Number
the addresses with a hash map, union every
address in an account with the account's first address, then group
the addresses by their root. The same trick handles "are these
equations consistent?" problems: union everything that's
==, then check that no != pair ended up in
the same group.
Counting islands
You can count the islands in a grid of land and water without
BFS or
DFS.
Give each cell its own number, row * width + col.
For each land cell, union it with the land cell to its right and the
land cell below it. The number of islands is the number of land
cells minus the number of unions that actually merged two groups.
For a single grid, BFS and DFS work just as well. Union-find pulls
ahead in the version where land is added one cell at a time and you
need the island count after every addition.
Union-Find vs. BFS and DFS
Breadth-first and depth-first search can answer the same connectivity questions. Which one to use depends on how the graph shows up:
| Union-find | BFS or DFS | |
|---|---|---|
| Best when | Edges arrive over time, and you need to answer "connected?" or "how many groups?" in between | The whole graph is known up front, and you explore it once |
| Time | O(α(V)) amortized per edge or query | O(V + E) per search, which you'd have to redo after every new edge |
| Memory | O(V). It doesn't need to store the edges at all. | O(V + E) for the adjacency list, plus O(V) for the visited set |
| Can it give you a path? | No. It only knows whether two items are connected. | Yes. BFS even finds the shortest path in an unweighted graph. |
| Deleting edges | Not supported. There's no way to split a group back apart. | Just search the updated graph again |
| Directed graphs | No. It only tracks undirected connectivity. | Yes: reachability, directed cycles, topological sort |
The short version: use union-find when connections only get added and you keep asking who's connected to whom. Use BFS or DFS when you need paths, distances, or edge directions, or when edges can be removed.
Common Union-Find Mistakes
-
Comparing
parententries instead of roots. In the example, after step 3,parent[1]is 0 andparent[3]is 2, but 1 and 3 are in the same group. Always comparefind(a)withfind(b). -
Linking the items instead of their roots. Writing
parent[a] = bmoves a (and everything under it) out of its old group, so the rest of that group is no longer connected to it. Always find both roots and link one root to the other. -
Updating the wrong size. Sizes only mean something at roots. After putting
rootBunderrootA, addrootB's size torootA's, not the other way around. -
Using it on a directed graph. With edges 0 → 1, 0 → 2, and 1 → 2, there's no directed cycle, but the third union finds 1 and 2 already connected and reports one. For directed graphs, use a DFS or topological sort instead.
-
Listing each undirected edge twice. If you build the edge list from an adjacency list, the edge between a and b shows up as both (a, b) and (b, a), and the second copy looks like a cycle. Only process each edge once.
-
Expecting to undo a union. Union-find can't delete an edge or split a group. If you know all the deletions ahead of time, a common trick is to process the operations in reverse order, so deletions become additions. Otherwise, use a graph search.
-
A recursive find on a tall tree. The popular one-line recursive find is fine with union by size, since trees stay at most log2 n tall. Without union by size, a long chain can overflow the call stack (Python's default recursion limit is 1,000). The two-loop find above avoids recursion entirely.
Classic Union-Find Problems
- Number of connected components (or "number of provinces"): union every edge, then return the group count.
-
Redundant connection: find the edge that turns a
tree into a graph with a cycle. It's the first edge whose
unionreturns false. - Graph valid tree: n nodes form a tree if there are exactly n - 1 edges and every union succeeds.
- Accounts merge and other "group the equivalent items" problems.
- Number of islands II: land is added one cell at a time, and you report the island count after each addition.
-
Satisfiability of equality equations: union the
==pairs, then check the!=pairs. - Minimum spanning tree with Kruskal's algorithm.
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake