Data Structures · Visualization
Disjoint Set: Union by Rank
Disjoint Set / Union-Find
Union by rank merges two groups by always attaching the tree with the smaller 'rank' (an estimate of tree height) underneath the root of the tree with the larger rank. Time: Nearly O(1) amortized (with path compression). Space: O(1) extra.
Big-O: Nearly O(1) with path compression and union by rank/size.
Disjoint Set: Union by Rank
Disjoint Set / Union-FindUnion by rank merges two groups by always attaching the tree with the smaller 'rank' (an estimate of tree height) underneath the root of the tree with the larger rank. This keeps the resulting tree as flat and shallow as possible, preventing find operations from becoming slow over time.
How Union by Rank Works
- Find the roots of both items being unioned.
- If they are already the same root, they're already in the same group — stop.
- Compare the rank of both roots.
- Attach the root with the smaller rank under the root with the larger rank; if ranks are equal, attach either way and increment the new root's rank by 1.
Union by Rank Worked Example
Input: Union groups rooted at A (rank 1) and B (rank 2)
- Find root of first item → A (rank 1)
- Find root of second item → B (rank 2)
- Rank of A < rank of B, so attach A under B
Output: B becomes the root of the merged group; A's rank stays 1
Press ▶ Run to watch it step by step.
def union(parent, rank, a, b):
ra, rb = find(parent, a), find(parent, b)
if ra == rb:
return
# attach smaller rank under bigger
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
# Union by rank keeps trees shallow
# example: union by rankBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Union by Rank Time & Space Complexity
When to Use Union by Rank
- Keeping merge trees shallow when combining many clusters/networks
- Used together with path compression to get the fastest possible Union-Find performance
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.