What is Disjoint Set
There are n nodes, numbered from 1. Each node starts in its own component. U a b merges the components of a and b. F a b returns 1 when a and b are already in the same component, otherwise 0.
Example. Union 1 with 2, and 3 with 4. Find 1 and 2 returns 1. Union 2 with 3, then find 1 and 4 returns 1 because the two pairs have been joined.
n = 5 U 1 2, U 3 4, F 1 2, U 2 3, F 1 4 Output: 1 1
Constraints. 1 ≤ n, q ≤ 105. This picture draws at most 6 nodes and 8 operations. Equal ranks attach b's root under a's root.
Approach
Interactive solution
The finished structure is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Find / union | O(α(n)) | Path compression and union by rank make each operation nearly constant. |
| Space | O(n) | One parent and one rank per node. |
Implementation
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[rb] < rank[ra]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1