Sub topic 6
Union by size: keeping trees shallow
This chapter assumes you know the parent-array forest, the find and union operations, and the naive chain case from the previous chapter. You should also be comfortable with Big-O and with logarithms.
The idea
The naive union always hangs the first root under the second. That choice ignores how big the trees are, so a large tree can end up underneath a single node and gain a level. Repeating this builds a chain.
Union by size changes one decision. When two roots are linked, the root of the smaller tree becomes a child of the root of the larger tree. Ties can go either way.
Implementation
Each root stores the size of its tree in a size array. Only the values at roots are meaningful, so you update size only for the root that survives.
parent = list(range(6))
size = [1] * 6
def find(x):
while parent[x] != x:
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False # already in the same set
if size[ra] < size[rb]:
ra, rb = rb, ra # make ra the larger root
parent[rb] = ra
size[ra] += size[rb]
return True
for i in range(5):
union(i, i + 1)
print(parent) # [0, 0, 0, 0, 0, 0]This is the same sequence of calls that built a chain 0 → 1 → 2 → 3 → 4 → 5 in the naive version. Now every node points directly at root 0, so each find takes one step.
Why the depth stays logarithmic
Follow a single node x. Its depth grows by one only when the root of its tree is attached under another root. That happens only when its tree is the smaller (or equal) of the two. So the merged tree has at least twice as many nodes as the tree x was in.
A node's set can double at most log2(n) times before it contains all n elements. Therefore:
- Every node has depth at most
floor(log2(n)). - Each
findtakes O(log n) time. - Each
uniontakes O(log n) time, because it is two finds plus constant work.
A tree of height h built this way contains at least 2^h nodes. That is the fact behind the bound.
Size versus rank
Some implementations store an upper bound on tree height, called rank, instead of size. They attach the lower-rank root under the higher-rank root, and increase the rank only when the two ranks are equal. Both rules give the same O(log n) height bound.
Size has two practical advantages. It is exact and easy to reason about. It is also useful by itself, since size[find(x)] tells you how large a component is.
Common errors
- Updating the wrong entry. After the swap,
size[ra] += size[rb]must use the root that stays. Adding to the child's entry leaves the real root with a stale size. - Comparing sizes of non-roots. Always call
findfirst. The size of an arbitrary node is not the size of its set. - Reading
size[x]for a non-root. Those entries are never updated after the node stops being a root, so they are out of date. - Skipping the equal-root check. If
ra == rb, linking a root under itself creates a cycle in the parent pointers, andfindthen loops forever.
Exercise
You run union-find with union by size on 16 elements and want the deepest possible tree. What is the maximum depth of any node, and what merge order reaches it?
Show answer
The maximum depth is 4, which is log2(16). Merge equal-size trees every time: first pair up the 16 singletons into 8 trees of size 2, then pair those into 4 trees of size 4, then 2 trees of size 8, then the final two. Each round adds one level to half of the nodes, and after four rounds the deepest nodes sit 4 edges below the root. No order can do worse, because a node's depth increases only when its set at least doubles.