Union-Find (Disjoint Set) — Connected Components — Complete Beginner Guide
Learning Objectives
- Model elements as parent pointers
- Implement find with path compression
- Implement union by rank or size
- Explain near constant amortized cost
- Count connected components in a graph
What Problem Does Union-Find Solve?
Union-find tracks a collection of disjoint sets and supports two operations.
| Operation | Question or Action |
|---|---|
| find | Which set owns this element |
| union | Merge two sets into one |
Classic uses include connected components, cycle detection, Kruskal minimum spanning tree, and account grouping by network connections.
Basic Parent Array
Each element points to a parent. Roots point to themselves and name their set.
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
self.count = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # path compression
return self.parent[x]
def union(self, a, b):
ra = self.find(a)
rb = self.find(b)
if ra == rb:
return False
# union by rank
if self.rank[ra] < self.rank[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
if self.rank[ra] == self.rank[rb]:
self.rank[ra] += 1
self.count -= 1
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
uf = UnionFind(6)
uf.union(0, 1)
uf.union(1, 2)
uf.union(3, 4)
print(uf.connected(0, 2)) # True
print(uf.connected(0, 3)) # False
print(uf.count) # components remaining
Path Compression
After find walks to the root, rewrite every visited node to point straight at the root. The next lookup becomes nearly free.
Without compression, chains degrade toward O(n) per find. With compression, long chains flatten after a few operations.
Union by Rank
Always attach the shorter tree under the taller tree. Rank approximates height without storing full height details.
| Technique | Effect |
|---|---|
| Naive parent link | Trees can become deep chains |
| Union by rank | Keeps height small |
| Path compression | Flattens during finds |
| Both combined | Amortized nearly O(1) |
Complexity
The inverse Ackermann function grows incredibly slowly. In practice it stays below five for any realistic n, so operations feel constant time.
| Variant | Time per Op |
|---|---|
| Naive | O(n) worst |
| Rank only | O(log n) |
| Compression only | O(log n) amortized |
| Rank plus compression | Nearly O(1) amortized |
| Space | O(n) |
Counting Connected Components
Initialize n sets. Union every edge. The final count attribute equals the number of components.
def count_components(n, edges):
uf = UnionFind(n)
for a, b in edges:
uf.union(a, b)
return uf.count
edges = [(0, 1), (1, 2), (3, 4)]
print(count_components(6, edges)) # 3
Cycle Detection
Add edges one by one. If an edge joins two nodes already connected, that edge closes a cycle.
def has_cycle(n, edges):
uf = UnionFind(n)
for a, b in edges:
if not uf.union(a, b):
return True
return False
print(has_cycle(3, [(0, 1), (1, 2), (0, 2)])) # True
Kruskal Preview
Kruskal sorts edges by weight and adds an edge only when its endpoints sit in different sets. Union-find answers that question fast and powers the whole algorithm.
Union-Find versus BFS Components
| Criteria | Union-Find | BFS or DFS |
|---|---|---|
| Incremental edges | Excellent | Needs rebuild |
| One-shot scan | Fine | Natural |
| Extra traversal detail | No paths stored | Can store paths |
| Complexity | Nearly linear total | O(V plus E) |
Union-Find Dry Runs
Trace a six-element union-find without optimizations first to see deep trees form. Then re-run the same unions with union by rank and path compression and compare heights. The optimized forest stays shallow because small trees attach under large ones and finds flatten paths as a side effect.
def show_parents(parent):
return list(parent)
parent = list(range(5))
# naive union makes 1 point to 0
parent[1] = 0
print(show_parents(parent))
# later find path compression rewires intermediate nodes
Use a step table for interviews:
| Step | Action | Parent Sketch | Count |
|---|---|---|---|
| 1 | init 0..4 | each roots | 5 |
| 2 | union 0 1 | 1 under 0 | 4 |
| 3 | union 2 3 | 3 under 2 | 3 |
| 4 | union 0 2 | tree under 0 | 2 |
| 5 | connected 3 1 | true after find | 2 |
Practice explaining why amortized cost stays nearly constant even though a single unlucky find could still walk a longer path.
Union-Find Versus Graph Search
Both union-find and BFS or DFS can label connected components, but they optimize for different situations.
Union-find thrives when edges arrive incrementally. You never rebuild a full adjacency structure; each new edge is a single union. Kruskal minimum spanning tree and offline connectivity questions lean on that property.
BFS or DFS thrives when the full graph is already stored and you also want paths, distances, or orderings. Component labels fall out as a byproduct of a standard traversal.
| Situation | Prefer |
|---|---|
| Edges stream over time | Union-find |
| Need actual path examples | BFS or DFS |
| Many connectivity queries during build | Union-find |
| Need neighbor lists for other algorithms | Adjacency list plus traversal |
| Cycle check while adding edges | Union-find |
Knowing both lets you match the tool to the data flow instead of forcing one pattern onto every problem.
Key Takeaways
💡
- Union-find maintains disjoint sets with find and union
- Path compression and union by rank deliver near O(1) operations
- Component counting needs only unions over all edges
- Cycle detection flags an edge that joins already connected nodes
- Kruskal shortest spanning tree logic depends on this structure
Practice Questions
- Trace union and find on elements zero through five without path compression and measure tree depth.
- Explain how union by rank prevents the worst deep-chain shape.
- Detect whether an undirected graph has a cycle using only union-find.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions