Data Structures · Visualization
Disjoint Set: Union by Size
Disjoint Set / Union-Find
Union by size is an alternative to union by rank that tracks the number of items in each group instead of an estimated height, and always attaches the smaller group under the root of the larger group. 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 Size
Disjoint Set / Union-FindUnion by size is an alternative to union by rank that tracks the number of items in each group instead of an estimated height, and always attaches the smaller group under the root of the larger group. This achieves the same goal — keeping trees shallow — and is often considered more intuitive since 'size' has an obvious real-world meaning.
How Union by Size Works
- Find the roots of both items being unioned.
- If they are already the same root, stop — already in the same group.
- Compare the size (item count) of both groups.
- Attach the root of the smaller group under the root of the larger group, and update the larger group's size to include the smaller group's items.
Union by Size Worked Example
Input: Union group A (size 3) and group B (size 5)
- Find root of A's group and root of B's group
- Size of A (3) < size of B (5), attach A's root under B's root
- Update B's group size to 3 + 5 = 8
Output: B becomes the root of the merged group of size 8
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 sizeBehind 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 Size Time & Space Complexity
When to Use Union by Size
- Merging clusters while tracking how large each cluster has grown
- Network/social-graph analysis where group size matters directly
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.