DSA Notes
Master Union-Find (Disjoint Set Union) in graph contexts — finding connected components, dynamic connectivity queries, cycle detection in undirected graphs, Kruskal
Union-Find Recap
Union-Find (DSU) maintains groups of elements and supports:
- Find(x): Which group is x in? Returns the root/representative.
- Union(x, y): Merge the groups containing x and y.
With path compression + union by rank: O(α(n)) ≈ O(1) per operation.
Application 2 — Cycle Detection in Undirected Graph
Application 3 — Redundant Connection
Application 4 — Dynamic Connectivity
class DynamicConnectivity:
"""
Support both edge additions and connectivity queries.
No edge removal (for removal, need more complex structures).
"""
def __init__(self, n):
self.dsu = DSU(n)
def add_edge(self, u, v):
self.dsu.union(u, v)
def are_connected(self, u, v):
return self.dsu.connected(u, v)
def num_components(self):
return self.dsu.components
def component_size(self, v):
return self.dsu.component_size(v)
dc = DynamicConnectivity(6)
dc.add_edge(0, 1)
dc.add_edge(2, 3)
print(dc.are_connected(0, 1)) # True
print(dc.are_connected(0, 2)) # False
print(dc.num_components()) # 4
dc.add_edge(1, 2)
print(dc.are_connected(0, 3)) # True (0-1-2-3)
print(dc.num_components()) # 3Application 5 — Largest Component
Application 6 — Accounts Merge
DSU vs BFS/DFS for Connected Components
| Feature | DSU | BFS/DFS |
|---|---|---|
| Time per query | O(α(n)) ≈ O(1) | O(V+E) for full traversal |
| Build time | O(E α(V)) | O(V+E) |
| Dynamic edges | ✅ — just call union | ❌ — must rebuild |
| Find path | ❌ — only connectivity | ✅ — can trace path |
| Detect cycles | ✅ | ✅ |
| Space | O(V) | O(V) |
Use DSU when: Only need connectivity (not path), edges are added dynamically. Use BFS/DFS when: Need actual paths, graph is static, need ordering.
Summary
DSU solves graph connectivity problems efficiently:
- Count components: Initialize n components, decrement on each union
- Cycle detection: Edge (u,v) creates cycle iff
find(u) == find(v) - Dynamic edges: Add edge with union, query connectivity with find
- Kruskal's MST: Core data structure for cycle-free edge addition
All operations O(α(n)) — essentially constant for all practical inputs.
*Next Lesson: Graph Interview Problems*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Union-Find (DSU) in Graphs — Connected Components and Dynamic Connectivity.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, union, find
Related Data Structures & Algorithms Topics