3.5.15 · D3Graphs

Worked examples — Disjoint Set Union (Union-Find) — path compression + union by rank → α(n)

2,431 words11 min readBack to topic

Before reading any example, keep these two code skeletons in view — every trace below is just these lines running:


The scenario matrix

Every DSU trace is built from a small set of case classes. If you cover all of them, you have covered DSU. Here they are:

# Case class What triggers it Which code branch
A Equal-rank union both roots have same rank tie → rank[rx] += 1
B Unequal-rank union one root taller hang smaller, no rank bump
C Union with self / already-same find(x) == find(y) early return
D Degenerate single node set of size 1, rank 0 parent[x] == x immediately
E Long chain + path compression many finds down a deep tree compression rewrites parent[]
F Word problem — connectivity "are these two connected?" repeated same()
G Kruskal MST edges sorted by weight, accept if roots differ union on accept, skip on same
H Cycle detection undirected edge whose endpoints already share a root detect via case C

The eight examples below hit all eight cells. Where geometry (the tree shape) matters, a figure carries it.


Example 1 — Equal-rank union (cell A)


Example 2 — Unequal-rank union: the short bows to the tall (cell B)


Example 3 — Union with self / already-same set (cell C)


Example 4 — Degenerate single node (cell D)


Example 5 — Long chain, then path compression flattens it (cell E)


Example 6 — Full mixed trace on (cells A + B + E together)


Example 7 — Word problem: friend network connectivity (cell F)


Example 8 — Kruskal MST + a cycle rejected (cells G + H)


Recall Which cell did each example cover?

Cover the right side and recite. Example 1 ::: A — equal-rank union, rank bumps by 1. Example 2 ::: B — unequal-rank union, no rank bump. Example 3 ::: C — already-same set, early return no-op. Example 4 ::: D — degenerate singleton, zero climbs. Example 5 ::: E — long chain flattened by path compression. Example 6 ::: A + B + E — full mixed six-element trace. Example 7 ::: F — connectivity word problem (components). Example 8 ::: G + H — Kruskal accept/reject + cycle detection.


Flashcards

In union, when does rank increase?
Only on a tie (equal ranks) — then the surviving root's rank .
After find(4) on chain with full compression, what is parent?
[0,0,0,0,0] — every node points straight at root 0.
Why does union(x,y) early-return when roots are equal?
The sets are already merged; proceeding could corrupt parent pointers or wrongly bump a rank.
In Kruskal, when is an edge rejected?
When its two endpoints already share a root (find(u)==find(v)) — accepting it would form a cycle.
How many edges does an MST on vertices have?
Exactly .