Union Find
Track which items share a group, with near-constant-time merges.
- current
- active this step
Everyone starts alone
Each node is its own root. Index 0 is unused because nodes are numbered from 1.
VARIABLES
- edge
- -
- parent[1..3]
- 1, 2, 3
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Union-Find (disjoint set union) keeps a parent pointer for every element. find returns a group’s root; union links two roots. Path compression and union by rank keep the trees flat.
Why it matters
Connectivity questions on a growing set of edges - “are these two connected yet?” - are answered in nearly O(1) each.
Think of it like this
Friend groups with one leader each: to check whether two people share a group, compare their leaders.
Use it when
- Connectivity as edges are added one by one
- Counting components
- Finding a redundant edge (a cycle) in an undirected graph
Avoid it when
- Edges are removed over time - union-find can’t split groups
- You need the actual path, not just connectivity
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| find or union, with both optimizations | O(α(n)) amortized | O(n) |
| Without optimizations | O(n) worst case | O(n) |
| Process E edges | O(E · α(n)) | O(n) |
Often confused with: BFS or DFS - they answer connectivity too, but rebuild from scratch after every new edge.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Edges arriving one by one with connectivity queries suggest union-find
- Kruskal’s minimum spanning tree is built on it
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Linking a and b directly instead of their roots
- Skipping path compression - find degrades to O(n)
- Off-by-one errors when nodes are numbered from 1
Edge cases to test
- A self-loop edge [x, x]
- Nodes numbered from 1 vs 0
- Every edge already inside one group
Knowledge check
Quick check to lock in the intuition.
Why union the two roots instead of the two nodes?
Practice
Apply what you just watched on real interview problems.