Learn / Graphs

Disjoint set union

A disjoint-set (union-find) structure keeps groups of elements: find(x) returns a representative of x's group and union(a, b) merges two groups. With path compression and union by size, both are almost O(1). It answers 'are these connected?' while edges keep arriving, which BFS cannot do cheaply.

How to recognise it

  • Groups that only merge, never split.
  • Many 'are a and b connected?' questions mixed with new connections.
  • Counting groups as edges or cells are added.

The structure

parent[x] = x; size[x] = 1
find(x): while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x]
union(a, b): ra = find(a); rb = find(b); if ra != rb: hang the smaller under the larger

The tree-and-forest picture is on the Structures page. Vertices, edges, adjacency lists and the other words used here are on the Structures page.

ProblemElements
network connectedcomputers; answer = groups - 1 if there are enough cables
accounts mergeaccounts, joined by a shared email
stonesrows and columns, joined by each stone
islands IIcells, joined to land neighbours as they appear

Common mistakes

  • Comparing parent[a] == parent[b] instead of find(a) == find(b).
  • Forgetting to count down the number of groups only when two different roots merge.

Problems

0 of 6 solved

Check yourself

What does find(x) return?

Why attach the smaller tree under the larger?

Stones sharing a row or column: how many can be removed?