Skip to content

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.

17 min read0/4 questions

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 next find on 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.

parent[] under union by rank and path compression
0
0
1
1
2
2
3
3
4
4
5
5
groups = 6

Six elements, each its own root: parent[i] = i, every rank 0.

1/8

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.

Python
class DSU: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.count = n # number of groups def find(self, x): root = x while self.parent[root] != root: root = self.parent[root] while self.parent[x] != root: # second pass: compress the path self.parent[x], x = root, self.parent[x] return root def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False # already connected if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra # ra is now the taller tree self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.count -= 1 return True def find_circle_num(is_connected): # Number of Provinces n = len(is_connected) dsu = DSU(n) for i in range(n): for j in range(i + 1, n): if is_connected[i][j]: dsu.union(i, j) return dsu.count def valid_tree(n, edges): # Graph Valid Tree if len(edges) != n - 1: return False dsu = DSU(n) return all(dsu.union(a, b) for a, b in edges) def redundant_connection(edges): # nodes are 1..n dsu = DSU(len(edges) + 1) for a, b in edges: if not dsu.union(a, b): return [a, b] assert find_circle_num([[1, 1, 0], [1, 1, 0], [0, 0, 1]]) == 2assert find_circle_num([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == 3assert valid_tree(5, [[0, 1], [0, 2], [0, 3], [1, 4]]) is Trueassert valid_tree(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]) is Falseassert valid_tree(4, [[0, 1], [2, 3], [1, 0]]) is Falseassert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]assert redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4] d = DSU(1000)for i in range(999): d.union(i, i + 1)assert d.count == 1 and max(d.rank) <= 10 # rank never exceeds log2(1000)print("provinces:", find_circle_num([[1, 1, 0], [1, 1, 0], [0, 0, 1]]))print("redundant:", redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.
Quick check
Which claim about union-find's cost is correct?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from collections import defaultdict class DSU: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n # union by size this time def find(self, x): root = x while self.parent[root] != root: root = self.parent[root] while self.parent[x] != root: self.parent[x], x = root, self.parent[x] return root def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.size[ra] < self.size[rb]: ra, rb = rb, ra self.parent[rb] = ra self.size[ra] += self.size[rb] return True def accounts_merge(accounts): dsu = DSU(len(accounts)) owner = {} # email -> first account index for i, (_, *emails) in enumerate(accounts): for email in emails: if email in owner: dsu.union(i, owner[email]) else: owner[email] = i groups = defaultdict(list) for email, i in owner.items(): groups[dsu.find(i)].append(email) return [[accounts[root][0]] + sorted(emails) for root, emails in groups.items()] accounts = [ ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["John", "johnsmith@mail.com", "john00@mail.com"], ["Mary", "mary@mail.com"], ["John", "johnnybravo@mail.com"],]result = sorted(accounts_merge(accounts))assert result == [ ["John", "john00@mail.com", "john_newyork@mail.com", "johnsmith@mail.com"], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"],]for row in result: print(row)
Output
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.

Adding land to a 3 x 3 grid, one cell at a time
100
000
000

Add (0,0). New island, no land neighbours. Count 1.

1/5

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.

Python
class DSU: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.count = 0 # counts islands, not elements def find(self, x): root = x while self.parent[root] != root: root = self.parent[root] while self.parent[x] != root: self.parent[x], x = root, self.parent[x] return root def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra == rb: return False if self.rank[ra] < self.rank[rb]: ra, rb = rb, ra self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 return True DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def num_islands_2(rows, cols, positions): dsu = DSU(rows * cols) land = set() out = [] for r, c in positions: cell = r * cols + c if cell in land: # duplicate addition out.append(dsu.count) continue land.add(cell) dsu.count += 1 for dr, dc in DIRS: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and nr * cols + nc in land: if dsu.union(cell, nr * cols + nc): dsu.count -= 1 out.append(dsu.count) return out def solve_surrounded(board): rows, cols = len(board), len(board[0]) border = rows * cols # the virtual node dsu = DSU(rows * cols + 1) for r in range(rows): for c in range(cols): if board[r][c] != "O": continue if r in (0, rows - 1) or c in (0, cols - 1): dsu.union(r * cols + c, border) for dr, dc in ((1, 0), (0, 1)): # right and down are enough nr, nc = r + dr, c + dc if nr < rows and nc < cols and board[nr][nc] == "O": dsu.union(r * cols + c, nr * cols + nc) safe = dsu.find(border) for r in range(rows): for c in range(cols): if board[r][c] == "O" and dsu.find(r * cols + c) != safe: board[r][c] = "X" assert num_islands_2(3, 3, [[0, 0], [0, 1], [1, 2], [2, 1], [1, 1]]) == [1, 1, 2, 3, 1]assert num_islands_2(2, 2, [[0, 0], [0, 0], [1, 1]]) == [1, 1, 2] board = [list("XXXX"), list("XOOX"), list("XXOX"), list("XOXX")]solve_surrounded(board)assert ["".join(row) for row in board] == ["XXXX", "XXXX", "XXXX", "XOXX"]print(num_islands_2(3, 3, [[0, 0], [0, 1], [1, 2], [2, 1], [1, 1]]))print(["".join(row) for row in board])
Output
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.

Python
import math def calc_equation(equations, values, queries): parent, weight = {}, {} # weight[x] = x / parent[x] def find(x): if parent[x] != x: p = parent[x] root = find(p) # now weight[p] = p / root weight[x] *= weight[p] parent[x] = root return parent[x] for (a, b), v in zip(equations, values): for x in (a, b): if x not in parent: parent[x], weight[x] = x, 1.0 ra, rb = find(a), find(b) if ra != rb: parent[ra] = rb weight[ra] = v * weight[b] / weight[a] out = [] for a, b in queries: if a not in parent or b not in parent or find(a) != find(b): out.append(-1.0) else: out.append(weight[a] / weight[b]) return out got = calc_equation([["a", "b"], ["b", "c"]], [2.0, 3.0], [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]])want = [6.0, 0.5, -1.0, 1.0, -1.0]assert all(math.isclose(g, w) for g, w in zip(got, want)), gotgot2 = calc_equation([["a", "b"], ["c", "d"], ["b", "d"]], [2.0, 4.0, 5.0], [["a", "c"]])assert math.isclose(got2[0], 2.5) # a = 2b, b = 5d, c = 4d, so a / c = 10d / 4dprint(got)
Output
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 the pairs0/5 matched

Match each problem to the union-find idea it needs.

Choose an item, then its match on the other side.
Quick check
A social app lets users unfriend each other, and you must answer 'are these two users connected through friends?' after every change. Why is plain union-find a poor fit?
Need a nudge? A hint rules out a wrong answer.
Key terms
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.