How to Implement Disjoint Set Union Find in Python
Implement a Disjoint Set Union-Find data structure using a Python dictionary for parent tracking, with path compression and connectivity checks.
Python code
34 linesclass DisjointSet:
def __init__(self):
self.parent = {}
def find(self, x):
# Path compression
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
# Initialize if not present
if x not in self.parent:
self.parent[x] = x
if y not in self.parent:
self.parent[y] = y
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
self.parent[root_x] = root_y
def connected(self, x, y):
return x in self.parent and y in self.parent and self.find(x) == self.find(y)
if __name__ == "__main__":
dsu = DisjointSet()
dsu.union(1, 2)
dsu.union(2, 3)
dsu.union(4, 5)
print("parent dict:", dsu.parent)
print("1 and 3 connected:", dsu.connected(1, 3))
print("1 and 4 connected:", dsu.connected(1, 4))
print("4 and 5 connected:", dsu.connected(4, 5))
Output
parent dict: {1: 2, 2: 3, 3: 3, 4: 5, 5: 5}
1 and 3 connected: True
1 and 4 connected: False
4 and 5 connected: True
How it works
The parent dictionary maps each element to its parent node. In find, path compression recursively updates each node to point directly to the root, making future lookups O(alpha(n)) almost constant time. union initializes missing keys, finds both roots, and attaches one root to the other. The connected method checks if both elements exist and share the same root. This implementation uses a dict instead of a list, allowing non-contiguous or non-integer elements like strings.
Common mistakes
- Forgetting to initialize missing keys before calling find
- Not using path compression, leading to O(n) chains
- Checking connectivity without verifying both elements exist
Variations
- Use union by rank with arrays for contiguous integer elements
- Add a `find_recursive` wrapper that handles missing keys gracefully
Real-world use cases
- Detecting connected components in social network graphs for friend suggestions.
- Grouping rows in a database migration tool to apply schema changes atomically.
- Tracking connectivity between network nodes or IoT devices in a monitoring system.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.