The user wants a program that implements a Union-Find (Disjoint Set) data structure.
I need to decide which programming language to use. Python, C++, and Java are common choices. Python is usually the most readable for explaining concepts, while C++/Java are often used in competitive programming or systems contexts. I will provide the implementation in Python for clarity, and perhaps mention how it works.
Core Concepts of Union-Find:
- Purpose: To keep track of a partition of a set of elements into disjoint subsets (connected components). It supports two primary operations efficiently.
- Operations:
Find(i): Returns the representative (root) of the set containing element i. Used to check if two elements are in the same set.
Union(i, j): Merges the sets containing elements i and j.
- Data Representation: usually a simple array (list)
parent where parent[i] is the parent of i. If parent[i] == i, i is the root.
- Optimizations:
- Path Compression: During
Find, we make every node on the path point directly to the root. This flattens the tree structure.
- Union by Rank (or Size): When merging two sets, we attach the smaller tree to the root of the larger tree. This keeps the tree balanced.
Plan:
- Define a class
UnionFind (or DisjointSet).
- Initialize the structure:
parent array where parent[i] = i.
rank array (initialized to 0) to track tree height/depth.
- Implement
Find(x):
- Base case: if
parent[x] == x, return x.
- Recursive/Iterative step: find root of parent.
- Optimization: Path compression (
parent[x] = find(parent[x])).
- Implement
Union(x, y):
- Find roots of
x and y (let's call them root_x and root_y).
- If roots are the same, they are already connected, return.
- Optimization: Union by Rank. Compare ranks of roots.
- If rank
root_x < rank root_y: attach root_x to root_y.
- If rank
root_x > rank root_y: attach root_y to root_x.
- If equal: attach one to the other and increment rank.
- Add a helper method
connected(x, y) to check if find(x) == find(y).
- Write a main block to demonstrate usage (e.g., creating sets, uniting elements, checking connectivity).
Language Choice: Python is best for readability.
Refining the Code (Self-Correction during thought process):
- Should I use recursion or iteration for Find? Recursion with path compression is elegant (
return self.parent[x] if self.parent[x] == x else (self.parent[x] := self.find(self.parent[x])) in Python 3.8+). Iteration is safer against recursion depth limits for huge inputs, but recursion is standard for teaching. I'll stick to standard recursion or a clear iterative approach. Let's use recursion for succinctness.
- Rank vs. Size? Rank is standard. Size is also fine. I'll stick to Rank.
Drafting the Class Structure:
class UnionFind:
def __init__(self, size):
self.parent = [i for i in range(size)]
self.rank = [0] * size
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):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
# union by rank
if self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
elif self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
This looks correct.
Example Scenario:
Create a graph scenario.
Edges: (1, 2), (2, 3), (4, 5).
Check: Are 1 and 3 connected? Yes.
Are 1 and 4 connected? No.
Union(3, 4).
Check: Are 1 and 5 connected? Yes.
I will present the Python code clearly, explain the logic, and provide the usage example. I will also briefly explain the time complexity (O(α(n))).
Here is an implementation of a Union-Find (Disjoint Set) data structure in Python.
This implementation uses Path Compression (in the find method) and Union by Rank (in the union method) to ensure the operations run in nearly constant time (O(α(n)), where α is the inverse Ackermann function).
Python Implementation
class UnionFind:
def __init__(self, size):
# The parent array holds the representative parent of each element.
# Initially, each element is its own parent (forms a set of size 1).
self.parent = [i for i in range(size)]
# The rank array approximates the height of the tree.
# It is used to optimize the merging process.
self.rank = [0] * size
# Optional: Track the number of disjoint sets
self.count = size
def find(self, x):
"""
Finds the representative (root) of the set containing element x.
Implements Path Compression: points nodes directly to the root
to flatten the structure for future queries.
"""
if self.parent[x] != x:
# Recursively find the root and update the parent pointer
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
"""
Merges the sets containing elements x and y.
Implements Union by Rank: Attaches the shorter tree to the
root of the taller tree to keep the structure balanced.
"""
root_x = self.find(x)
root_y = self.find(y)
# If they are already in the same set, do nothing
if root_x == root_y:
return False
# Union by Rank logic
if self.rank[root_x] < self.rank[root_y]:
# Root X's tree is shorter, attach it to Root Y
self.parent[root_x] = root_y
elif self.rank[root_x] > self.rank[root_y]:
# Root Y's tree is shorter, attach it to Root X
self.parent[root_y] = root_x
else:
# Ranks are equal, pick one as root (arbitrarily X) and increment its rank
self.parent[root_y] = root_x
self.rank[root_x] += 1
self.count -= 1
return True
def connected(self, x, y):
"""
Checks if elements x and y are in the same set.
"""
return self.find(x) == self.find(y)
# --- Usage Example ---
if __name__ == "__main__":
# Initialize 5 elements (0, 1, 2, 3, 4)
uf = UnionFind(5)
print("Initial state:")
print(f"Parent array: {uf.parent}")
# Perform unions
print("\nUniting 0 and 1...")
uf.union(0, 1)
print("Uniting 2 and 3...")
uf.union(2, 3)
print(f"Parent array: {uf.parent}")
# Note: 1 points to 0 (or vice versa depending on rank), 3 points to 2
print("\n--- Checks ---")
# Check connectivity
print(f"Are 0 and 1 connected? {uf.connected(0, 1)}") # True
print(f"Are 1 and 2 connected? {uf.connected(1, 2)}") # False
print("\nUniting 1 and 2 (merging sets {0,1} and {2,3})...")
uf.union(1, 2)
print(f"Are 0 and 3 connected? {uf.connected(0, 3)}") # True
print(f"Are 4 and 0 connected? {uf.connected(4, 0)}") # False
Key Concepts Explained
parent Array: This tracks the immediate parent of every node. If a node is a root (the representative of a set), its parent is itself.
- Path Compression (
find): When we look for the root of a node, we recursively travel up the tree. To speed up future searches, we update the nodes along the path to point directly to the root. This keeps the tree very flat.
- Union by Rank (
union): When merging two sets, we want to avoid making a tall tree even taller. We attach the root of the "shorter" tree to the root of the "taller" tree. rank is an approximation of tree height.