Union-Find (Disjoint Set Union)
Track groups as trees with one root each: `find` returns the root, `union` links two roots, and with path compression plus union by rank both run in near-constant amortized time.
Analogy: Each club member knows someone closer to the president. To check if two people share a club, both follow the chain up to their president; merging two clubs means one president now reports to the other.
How it works
- Each element points to a parent; the root of its tree names the group.
unionfinds both roots: equal roots mean the edge closes a cycle; otherwise one root goes under the other.- Path compression flattens paths during
find; union by rank keeps trees shallow. - Together: amortized O(α(n)) per operation; α(n) ≤ 4 for any realistic n, so effectively constant.
- Fits when edges arrive incrementally and you ask "same group?"; it cannot split groups.
Check yourself
Answer to mark it learned; your answers aren't scored.
A social app adds friendships as a stream. After each new friendship you must report how many friend groups exist. 100,000 users, 100,000 friendships. What do you build?
Go deeper
Solve it in Python 9
- Cheapest cables to connect every sitemedium
- Count the connected groupsmedium
- Extra cable in the networkmedium
- Merge contact cards that share an emailmedium
- Remove stones sharing a row or columnmedium
- Smallest string from allowed swapsmedium
- Unit conversions from known factsmedium
- Islands after each new land cellhard
- Reachable using only short roadshard
Full explanation
Union-find keeps a parent array: each element points toward the root that represents its group.
find(x): follow parents up to the root.union(a, b): find both roots; if they differ, put one under the other.
Two optimizations make it fast:
- Path compression: during
find, point every visited node straight at the root, so the next lookup is one hop. - Union by rank (or size): hang the shorter tree under the taller one, so trees stay shallow.
Together they give amortized O(α(n)) per operation, where α is the inverse Ackermann function: at most 4 for any realistic n, so effectively constant.
Signals: edges arrive one at a time and you ask "same group?" between them; count components; detect a cycle in an undirected graph; merge equivalent items (accounts sharing an email). For one query on a static graph, a plain Graph traversal: BFS and DFS is just as good. Union-find cannot split groups.
Code DSU with path compression and union by rank
class DSU:
def __init__(self, n: int):
self.parent = list(range(n)) # every node starts as its own root
self.rank = [0] * n # upper bound on tree height
self.count = n # number of components
def find(self, x: int) -> int:
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # path compression
return self.parent[x]
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # same set: edge (a, b) closes a cycle
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra # shorter tree under the taller root
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
self.count -= 1
return True
def redundant_edge(n: int, edges: list[list[int]]) -> list[int]:
dsu = DSU(n + 1) # nodes are 1..n
for a, b in edges:
if not dsu.union(a, b):
return [a, b]
return []Real example
Redundant connection. A tree of n nodes got one extra edge; return the edge that closes the cycle. Feed the edges to union in order: the first one whose endpoints already share a root is the answer. For [1,2], [1,3], [2,3]: the first two unions merge everything, then union(2, 3) finds equal roots and returns false, so the answer is [2,3]. O(n·α(n)) time, O(n) space, and no adjacency list.
Trade-offs +3 · −3
+ You gain
- Near-constant time per operation, even as groups merge online.
- About 20 lines; no adjacency list or graph rebuild needed.
- Counts components for free: subtract one on every successful union.
− You pay
- Groups only merge: no edge deletions or splits.
- Answers "same group?", not the path or distance between nodes.
- The array version needs integer ids; map strings to indexes or use a dict.
Use it when
Edges or equivalences arrive one by one and you need "connected?" or component counts between them: Kruskal's MST, cycle detection in undirected graphs, merging accounts, islands added over time.
Avoid it when
You need the actual path, shortest distances, directed reachability or edge deletions. For one query on a static graph, a single BFS/DFS is simpler.
Numbers to know 4
- Both optimizations: amortized O(α(n)) per operation; α(n) ≤ 4 for any realistic n (Tarjan, 1975).
- Union by rank alone: O(log n) per
find; rank never exceeds ⌊log₂ n⌋. - Kruskal's MST: O(E log E), dominated by sorting the edges.
- Space: O(n) for
parentandrank.
Common pitfalls 4
- Testing
parent[a] == parent[b]instead offind(a) == find(b): a parent is not always the root. - Linking nodes (
parent[b] = a) instead of roots (parent[rb] = ra): the sets never fully merge. - Recursive
findwithout union by rank: a long chain can exceed Python's 1,000-frame recursion limit. - 1-indexed nodes in an array of size n: allocate
n + 1slots.
Interview questions 2
Answer out loud first, then reveal.
How do you recognize a union-find problem?Show answer
I look for connectivity questions mixed with merges: "after each new edge, how many groups?", "which edge creates a cycle?", "are these two accounts the same person?". If the graph is static and I ask once, BFS or DFS is just as good and can also return the path. If edges get deleted or direction matters, union-find doesn't fit; when deletions are known in advance, I process them in reverse, as additions.
What variants of union-find come up in interviews?Show answer
Three. Size per root, summed on union, answers "largest group". Weighted union-find stores each node's ratio or offset to its parent, for equation problems like a / b = 2, b / c = 3. Kruskal's MST sorts edges by weight and keeps each edge whose union succeeds; the sort dominates at O(E log E). For string keys I use a dict as the parent map instead of an array.