File tree 1 file changed +56
-0
lines changed
data_structures/disjoint_set
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Union-Find (Disjoint Set Union) with Path Compression and Union by Rank
3
+
4
+ Use Case:
5
+ - Efficient structure to manage disjoint sets
6
+ - Useful in network connectivity, Kruskal's MST, and clustering
7
+
8
+ Time Complexity:
9
+ - Nearly constant: O(α(n)) where α is the inverse Ackermann function
10
+
11
+ Author: Michael Alexander Montoya
12
+ """
13
+
14
+ class UnionFind :
15
+ def __init__ (self , size ):
16
+ self .parent = list (range (size ))
17
+ self .rank = [0 ] * size
18
+
19
+ def find (self , node ):
20
+ if self .parent [node ] != node :
21
+ self .parent [node ] = self .find (self .parent [node ]) # Path compression
22
+ return self .parent [node ]
23
+
24
+ def union (self , x , y ):
25
+ rootX = self .find (x )
26
+ rootY = self .find (y )
27
+
28
+ if rootX == rootY :
29
+ return False # Already connected
30
+
31
+ # Union by rank
32
+ if self .rank [rootX ] < self .rank [rootY ]:
33
+ self .parent [rootX ] = rootY
34
+ elif self .rank [rootX ] > self .rank [rootY ]:
35
+ self .parent [rootY ] = rootX
36
+ else :
37
+ self .parent [rootY ] = rootX
38
+ self .rank [rootX ] += 1
39
+
40
+ return True
41
+
42
+
43
+ # Example usage
44
+ if __name__ == "__main__" :
45
+ uf = UnionFind (10 )
46
+
47
+ uf .union (1 , 2 )
48
+ uf .union (2 , 3 )
49
+ uf .union (4 , 5 )
50
+
51
+ print ("1 and 3 connected:" , uf .find (1 ) == uf .find (3 )) # True
52
+ print ("1 and 5 connected:" , uf .find (1 ) == uf .find (5 )) # False
53
+
54
+ uf .union (3 , 5 )
55
+
56
+ print ("1 and 5 connected after union:" , uf .find (1 ) == uf .find (5 )) # True
You can’t perform that action at this time.
0 commit comments