Unit 5 of 9 · about 3 hours · implement
Union-find with path compression and union by rank
Connectivity queries that interleave with edge insertions defeat repeated traversal: each BFS costs a full scan while each union-find operation costs effectively constant time.
You'll be able to
- Implement union-find with path compression and union by rank or size, and state the amortized inverse-Ackermann bound with its source.
- Identify when union-find cannot help: deletions, directed reachability and queries that need paths, not just connectivity.
- Choose the online union-find framing over one-shot BFS or DFS when edges arrive interleaved with queries.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Union-Find: parent forests, path compression, and union by rankDSA Handbook - graphs
The forest, the find, the union; Two heuristics that change the bound; Putting it all together (LC 684); LC 990: equality and inequality, two passes
Skim LC 685's directed case-split on first pass; return after the MST unit if directed redundancy still bites.
- Disjoint Sets, Lecture Note 11Algorithms - graph chapters
11.1 Reversed Trees (union by depth or rank, and the size-at-least-2-to-the-rank property); 11.3 Path Compression; 11.6 The Ackermann Function and its Inverse for the bound. Skim 11.2 Shallow Threaded Trees.
Focus on
- Compare
find(x)withfind(y), neverparent[x]withparent[y]: cousins share a root through a chain while their immediate parents differ. - Rank is an upper bound on height, not the height: compression shrinks trees without lowering ranks, and the size-at-least-2-to-the-rank property is what the log bound leans on.
- Count components as the set of
find(i)over all , never as the set ofparententries: stale intermediate pointers undercount. - Process all equalities before any inequality (LC 990): input order lies, because a later union can connect an earlier checked pair.
Common mistakes · 3
- Rank without compression, or compression without rank: the adversarial chain
union(0,1),union(1,2), ... builds depth when attachment is one-sided, and compression never fires before the firstfind. - Recursive
findon production-size chains: fine at LC 684 scale (), but the recursive form costs a frame per hop. Ship the iterative two-pass form past elements. - String keys without make-set: integer constructors pre-fill every root, but email-keyed maps need an explicit make on first sighting or
findraisesKeyError.
Try it yourself
Closed-book, before checking anything
[[1,2],[1,3],[2,3]] and return [2,3] as the first redundant edge. Then union the chain 0-1 through 6-7 in order with union by rank and report maximum depth 1.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Derive the bound for union by rank alone.Answer
A rank- root has at least descendants (equal-rank merges double the set), so a tree on nodes has rank at most , and find walks at most that many parent pointers.
2.Why do two passes decide LC 990 correctly?Answer
Pass one builds every equivalence class the equalities force. Pass two checks each inequality against the final partition: any same-set inequality contradicts the input, and no order dependence remains because all unions precede all checks.
3.Give two queries union-find cannot answer.Answer
Deletions (parent pointers only merge; splitting needs a rebuild) and directed reachability or path queries (roots record connectivity, not direction or routes).
4.What does mean in practice?Answer
Tarjan's bound says operations cost ; stays at most 4 for any storable , so every operation is effectively constant, and the 1979 lower bound says no pointer-machine structure beats it.
Practice
- LeetCode 684: Redundant Connection
Examples 1 (
[[1,2],[1,3],[2,3]]answers[2,3]) and 2 (five-edge graph)The first
unionreturningFalseis the answer. After-attempt reference is the DSA Handbook 8.8 worked example and trace. - LeetCode 990: Satisfiability of Equality Equations
The two listed examples (
a==bwithb!=aanswersFalse; the satisfiable set answersTrue)Two passes: unions first, inequality checks second. After-attempt reference is the LC 990 section of DSA Handbook 8.8.
You're done when
Your blank-file DSU prints [2,3] on the redundant input with max chain depth 1, and LC 684 plus LC 990 pass with roots compared, never parents.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 3 more in the section
- DSA Handbook - graphsHandbook Academy · primary
Study all of Part 8 in order. For each algorithm, write the representation, invariant, forbidden input assumptions and independently checkable output before reading the implementation.
- Algorithms - graph chaptersJeff Erickson · required
Use the basic graph, depth-first search, minimum spanning tree, shortest path and flow chapters, and lecture note 11 Disjoint Sets for union-find, for correctness proofs and counterexamples to tempting wrong algorithms.
Also in this section
- AlgoMaster DSA - graph sliceAlgoMaster · required
Attempt Number of Islands, Course Schedule II and Network Delay Time cold. They cover traversal, dependency modeling and weighted shortest paths; add one narrative problem only if graph modeling remains weak.
- Hypothesis - generated graph testsHypothesis · support
Generate small sparse, dense, disconnected, cyclic, parallel-edge and weighted graphs. Compare optimized results with exhaustive or deliberately simple references and retain shrunk failures.
- NeetCode - unseen graph problemsNeetCode · optional
Use two unseen story problems without graph tags. Grade the model, assumptions, certificate and tests as well as the final answer.