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.
| Problem | Elements |
|---|---|
| network connected | computers; answer = groups - 1 if there are enough cables |
| accounts merge | accounts, joined by a shared email |
| stones | rows and columns, joined by each stone |
| islands II | cells, joined to land neighbours as they appear |
Common mistakes
- Comparing
parent[a] == parent[b]instead offind(a) == find(b). - Forgetting to count down the number of groups only when two different roots merge.
Problems
- Disjoint Setmediumguide ready
- Number of Operations to Make Network Connectedmediumguide ready
- Accounts Mergemediumguide ready
- Most Stones Removed with Same Row or Columnmediumguide ready
- Number of Islands IIhardguide ready
- Making A Large Islandhardguide ready