Lesson 21 of 40Graphs in depth
Union-Find in Depth
Build a disjoint set union with union by rank and path compression, then use it for components, cycles, online islands, grids and ratio queries.
A support team merges duplicate customer accounts whenever two records share an email or phone number. Records arrive all day, and every merge can join two groups that were each already the result of many merges. You need two answers fast and often: "are these two records the same customer?" and "how many distinct customers are there now?". Rebuilding a graph and running a search after every new record would redo almost all of the work each time. Union-find answers both questions in effectively constant time per operation, and it is the structure behind Kruskal's algorithm, account merging, image labelling and a large family of interview problems.
What union-find stores
Graphs introduced the idea briefly: every element points at a parent, and following parents ends at a root that names the group. find(x) returns the root of x's group. union(a, b) makes one root point at the other, merging two groups. Two elements are connected exactly when they have the same root.
The structure is a forest of trees stored in a single array. It does not record which edges you added or how two elements are connected, only that they are. That loss of detail is the price of the speed, and it explains everything union-find cannot do (more on that below).
Two small optimisations turn the naive version, which can be O(n) per call, into the near constant-time version:
- Union by rank (or by size): always attach the shorter tree under the taller one. A tree's height can only grow when you join two trees of equal rank, and that needs at least double the elements, so heights stay at most log n.
- Path compression: during
find, point every node you passed straight at the root. The nextfindon any of them takes one step.
With both, a sequence of m operations on n elements costs O(m · α(n)), where α is the inverse Ackermann function. α grows so slowly that it is at most 4 for any n you could ever store, so in practice each operation is constant time. With only one of the two optimisations, the bound is O(log n) per operation (worst case for rank alone, amortised for compression alone). Interviewers like to check that you know it takes both.
Six elements, each its own root: parent[i] = i, every rank 0.
A complete implementation
This is the version to write in an interview. find is iterative, so a long chain can never hit Python's recursion limit, and it does full path compression in a second pass. union returns whether it merged anything, which is exactly the "did this edge create a cycle?" signal many problems need. count tracks the number of groups as merges happen, so you never have to scan for roots.
Press Run (⌘ Enter) to see what happens.A few details are worth saying out loud. Graph Valid Tree needs two checks: exactly n - 1 edges, and no edge that joins two nodes already connected. Either alone is not enough: four nodes with three edges can contain a triangle plus an isolated node. Redundant Connection returns the first edge whose endpoints already share a root, because in a tree plus one edge, that is the edge that closes the only cycle. Union by size is the common alternative to rank: attach the smaller group under the larger and add the sizes. It gives the same bound, and you get each group's size for free, which "largest component" problems need.
What does this print?
parent = list(range(5))
def find(x):
steps = 0
while parent[x] != x:
x = parent[x]
steps += 1
return x, steps
for i in range(4):
ra, _ = find(i)
rb, _ = find(i + 1)
parent[ra] = rb # no rank, no compression
print(find(0))Merging by shared keys: Accounts Merge
In Accounts Merge, each account is a name plus a list of emails, and two accounts belong to the same person if they share any email. The insight is to union on emails, not on accounts. Give each email the index of the first account that listed it. When a later account lists the same email, union the two account indices. At the end, group emails by the root of their account and sort each group.
This is the customer-deduplication problem from the introduction in miniature, and it is how you would write it at work too: map each key (email, phone, device id) to an integer id once, then union ids. Mapping to integers keeps the parent array a plain list, which is faster and smaller than a dictionary of strings.
Press Run (⌘ Enter) to see what happens.The two Johns stay separate because they share no email: names are not keys. Complexity is dominated by sorting the emails, O(E log E) for E emails in total, with near-constant work per union.
Online connectivity: Number of Islands II
Graphs counted islands with one flood fill over a finished grid. Number of Islands II changes the question: the grid starts as water, land is added one cell at a time, and you must report the island count after every addition. Re-running a flood fill after each step costs O(rows · cols) per step. Union-find handles each addition in near-constant time, because adding land is purely a merge.
For each new land cell: if it is already land, report the same count again (a classic trap in the test data). Otherwise count it as a new island, then union it with each of its land neighbours, and every union that actually merges reduces the count by one. Grid cells become integer ids with r * cols + c, so the parent array is flat.
Add (0,0). New island, no land neighbours. Count 1.
Surrounded Regions shows another grid trick: the virtual node. You must flip every O region that does not touch the border into X. Add one extra id, rows * cols, that stands for "the border". Union every border O with it, and union every O with its O neighbours. Afterwards, an O survives exactly when it is connected to the virtual node. The same idea, one extra node that stands for "outside" or "the top row", solves percolation-style problems such as Bricks Falling When Hit.
Press Run (⌘ Enter) to see what happens.Weighted union-find: Evaluate Division
Evaluate Division gives equations such as a / b = 2 and b / c = 3, then asks for a / c (6), b / a (0.5), or a / e (unknown, so -1). You can solve it with a DFS from each query, but a weighted union-find answers each query in near-constant time.
Store, next to each parent pointer, the ratio weight[x] = x / parent[x]. During find, multiply the weights along the path, so after compression weight[x] = x / root. To answer a / b, check that they share a root, then return weight[a] / weight[b], because (a / root) / (b / root) = a / b. To union with a / b = v, attach root ra under root rb with weight ra / rb = v · weight[b] / weight[a]. The same "store an offset to the parent" pattern solves problems about relative positions, parity ("are these two in the same or opposite group?"), and accounting where amounts are known only relative to each other.
Press Run (⌘ Enter) to see what happens.This find is recursive for readability. The tree stays shallow on interview inputs, but for millions of chained equations you would convert it to the iterative two-pass form.
When not to use union-find
Union-find answers one question: are these two things in the same group? Reach for something else when the problem needs more:
- You need a path, its length, or the actual route. Union-find forgets edges. Use BFS or DFS, or the algorithms in Shortest Paths.
- Edges are deleted. There is no efficient "split". The standard trick for offline problems, where all operations are known in advance, is to reverse time: start from the final graph and replay deletions backwards as additions.
- Directed reachability. Union-find treats connections as symmetric, so it cannot say "A reaches B but B does not reach A". Directed cycle detection needs DFS colouring or Kahn's algorithm.
- The graph is static and you need one answer. A single BFS or DFS over a finished adjacency list is O(V + E), just as fast, and you may need the traversal anyway. Union-find shines when edges arrive over time, when you get many connectivity queries mixed with merges, or when the input is a bare edge list you would otherwise have to turn into an adjacency list.
Kruskal's minimum spanning tree algorithm is the most famous user of union-find: sort edges by weight and keep each edge only if union returns true. You will build it in Minimum Spanning Trees.
Match each problem to the union-find idea it needs.
- disjoint set union
- Another name for union-find: a forest where each tree is one group, named by its root.
- path compression
- During
find, point every visited node at the root so later finds take one step. - union by rank
- Attach the root with the smaller rank under the larger one. Keeps tree height at most log n.
- union by size
- Attach the smaller group under the larger one. Same bound as rank, and it gives group sizes.
- inverse Ackermann
- The function α(n) in union-find's amortised bound. It is at most 4 for any practical n.
- virtual node
- An extra id that stands for a region such as the border, so one union can mean 'touches the edge'.
- weighted union-find
- Union-find that also stores a value relative to the parent, such as a ratio or parity.