Skip to content

Instantly share code, notes, and snippets.

@siavashk
Created December 2, 2024 23:26
Show Gist options
  • Save siavashk/fef678f9f2ef17fdc6cff917922bf4ba to your computer and use it in GitHub Desktop.
Save siavashk/fef678f9f2ef17fdc6cff917922bf4ba to your computer and use it in GitHub Desktop.
Disjoint Set Implementation
class UnionFind:
def __init__(self):
self.parent = {}
self.rank = {}
def add(self, x):
"""
Adds a new element to the Union-Find structure.
Initializes the element as its own parent (singleton set).
"""
if x not in self.parent:
self.parent[x] = x # Parent of itself
self.rank[x] = 0 # Rank is initially 0
def find(self, x):
"""
Finds the representative (root) of the set containing x.
Uses path compression for optimization.
"""
if x not in self.parent:
raise ValueError(f"Element {x} is not in the structure. Use 'add' to add it first.")
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]) # Path compression
return self.parent[x]
def union(self, x, y):
"""
Merges the sets containing x and y.
Uses union by rank for optimization.
"""
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
# Union by rank
if self.rank[root_x] > self.rank[root_y]:
self.parent[root_y] = root_x
elif self.rank[root_x] < self.rank[root_y]:
self.parent[root_x] = root_y
else:
self.parent[root_y] = root_x
self.rank[root_x] += 1
def connected(self, x, y):
"""
Checks if two elements are in the same set.
"""
return self.find(x) == self.find(y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment