1. Understand the Goal: The user wants a program implementing a Union-Find (Disjoint Set Union - DSU) data structure.
-
Identify Key Concepts of Union-Find:
- What is it? A data structure that keeps track of a partition of a set of elements into disjoint (non-overlapping) subsets.
- Core Operations:
makeSet(x): Creates a new set containing only element x.
find(x): Returns the representative (root) of the set containing element x. (Used to check if two elements are in the same set).
union(x, y): Merges the sets containing x and y.
- Optimizations (Crucial for a "good" implementation):
- Path Compression: Flattens the structure of the tree during
find. Makes future queries faster.
- Union by Rank (or Union by Size): Attaches the shorter tree to the root of the taller tree during
union. Keeps the tree shallow.
-
Select Programming Language: Python is generally accessible and pseudocode-like, making it a good default choice. However, providing C++ or Java as well might be helpful for students or those in specific environments. I will stick to Python for clarity but structure it as a class.
-
Drafting the Implementation (Python):
-
Class Name: UnionFind or DisjointSet.
-
Initialization (__init__): Needs to handle n elements.
parent: An array where parent[i] is the parent of node i. Initially, each node is its own parent.
rank: An array to store the rank (approximate height) of the tree rooted at i. Initially 0.
-
Find Method (find):
- Base case: If
parent[x] == x, return x.
- Recursive step with Path Compression:
parent[x] = find(parent[x]). Return parent[x].
- Alternative Iterative: Loop until root, then update pointers. Recursive is elegant and standard for Python.
-
Union Method (union):
- Find roots of both elements:
rootX = find(x), rootY = find(y).
- If
rootX == rootY, they are already in the same set. Return.
- Union by Rank logic:
- If
rank[rootX] < rank[rootY]: Attach rootX to rootY.
- If
rank[rootX] > rank[rootY]: Attach rootY to rootX.
- If equal: Attach one to the other (arbitrary) and increment the rank of the new root.
-
Connected Method (Optional but useful):
- Returns
find(x) == find(y).
-
Refining the Code:
- Make sure to handle edge cases (though usually UF assumes 0 to n-1 indices).
- Add comments explaining Path Compression and Union by Rank.
-
Structuring the Output:
- Explanation: Briefly explain what it is and the optimizations.
- Code: The actual Python code.
- Usage Example: A script showing how to instantiate and use it.
- Complexity Analysis: Mention the Inverse Ackermann function time complexity (practically O(1)).
-
Drafting the response (Mental or Scratchpad):
- Intro: Union-Find manages disjoint sets.
- Optimizations: Mention Rank and Path Compression.
- Code:
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.rank = [0] * size
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, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX == rootY: return
# 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
- Example: Create size 5. Union 0-1. Union 2-3. Check connected. Union 1-2. Check connected.
-
Review against User Request: The user asked for "a program". The plan above provides a robust, optimized implementation. I should ensure the code is clean and runnable.
-
Final Polish: Ensure variable names are descriptive (parent, rank). Add docstrings.
(Self-Correction during drafting): Should I use "size" or "rank" for the optimization? Rank is standard, Size works too. I'll stick with Rank as it's the classic textbook definition for union by height. I will also add a connected helper method because it makes the API cleaner for users.
- Final Output Generation: (This matches the provided good response).
Here is a clean, efficient 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 achieve near-constant time complexity.
Python Implementation
class UnionFind:
def __init__(self, size):
"""
Initialize the Union-Find structure.
Each element is initially its own parent (its own set).
Rank is used to optimize the union operation.
"""
if size <= 0:
raise ValueError("Size must be greater than 0")
self.parent = [i for i in range(size)]
self.rank = [0] * size
self.size = size
def find(self, x):
"""
Finds the representative (root) of the set containing element x.
Implements Path Compression: flattens the structure of the tree
so future queries are faster.
"""
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):
"""
Unions (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 tree balanced.
"""
root_x = self.find(x)
root_y = self.find(y)
# If they are already in the same set, no action needed
if root_x == root_y:
return False
# Union by rank logic
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:
# If ranks are equal, assign one as parent and increment its rank
self.parent[root_y] = root_x
self.rank[root_x] += 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)
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# Initialize with 5 elements (0, 1, 2, 3, 4)
uf = UnionFind(5)
print("Initial state:")
print(f"Parent array: {uf.parent}")
# Output: [0, 1, 2, 3, 4] (everyone is their own parent)
# Perform unions
print("\nUniting 0 and 1...")
uf.union(0, 1)
print("Uniting 2 and 3...")
uf.union(2, 3)
print("Uniting 1 and 2...")
uf.union(1, 2)
# This merges set {0,1} with set {2,3} -> {0,1,2,3}
print(f"\nParent array after unions: {uf.parent}")
# Check connections
print(f"\nAre 0 and 3 connected? {uf.connected(0, 3)}") # True
print(f"Are 1 and 2 connected? {uf.connected(1, 2)}") # True
print(f"Are 0 and 4 connected? {uf.connected(0, 4)}") # False (4 is isolated)
Explanation of Key Concepts
parent Array: This array tracks the parent of every node. If parent[i] == i, then i is the root (representative) of its set.
find(x) (Path Compression):
- Standard approach: Climb up the tree until you find the root.
- Optimization: As we climb up, we update the nodes to point directly to the root. This flattens the tree structure, making future lookups incredibly fast (almost O(1)).
union(x, y) (Union by Rank):
- Standard approach: Attach the root of
x to the root of y.
- Optimization: We check the
rank (an estimate of tree height). We always attach the smaller tree under the root of the larger tree. This keeps the tree from becoming a long, linked-list-like chain.
Time Complexity
With both Path Compression and Union by Rank, the time complexity for operations is **O(α(n))), which is extremely slow-growing. For all practical purposes, operations run in O(1) (constant) time.