Advanced · Union-Find · Components

Disjoint Set Visualizer

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

Find Follow parent links to the root. Path compression then points every visited node directly at that root, so the next find is shorter.
Union by rank Link the root with the smaller rank under the other root. When the ranks are equal, link one under the other and increase the surviving root's rank.

Interactive solution

Parent forest
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
Step 0/0 Answer —

The finished structure is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
Find / unionO(α(n))Path compression and union by rank make each operation nearly constant.
SpaceO(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