File tree Expand file tree Collapse file tree 1 file changed +16
-4
lines changed
datastructures/sets/union_find Expand file tree Collapse file tree 1 file changed +16
-4
lines changed Original file line number Diff line number Diff line change @@ -46,17 +46,29 @@ def get_count(self) -> int:
4646
4747
4848class UnionFind :
49- def __init__ (self , size ):
49+ """A minimal Union-Find data structure with path compression."""
50+
51+ def __init__ (self , size : int ):
52+ """Initializes the data structure with 'size' elements."""
53+ if size <= 0 :
54+ raise ValueError ("Size must be a positive integer." )
5055 self .parent = list (range (size ))
5156
52- def find (self , x ):
57+ def find (self , x : int ) -> int :
58+ """Finds the representative (root) of the set containing element 'x'."""
5359 if self .parent [x ] != x :
5460 # Path compression
5561 self .parent [x ] = self .find (self .parent [x ])
5662 return self .parent [x ]
5763
58- def union (self , x , y ):
64+ def union (self , x : int , y : int ) -> bool :
65+ """
66+ Merges the sets containing elements 'x' and 'y'.
67+ Returns True if a merge occurred, False if already in same set.
68+ """
5969 root_x = self .find (x )
6070 root_y = self .find (y )
6171 if root_x != root_y :
62- self .parent [root_y ] = root_x
72+ self .parent [root_y ] = root_x
73+ return True
74+ return False
You can’t perform that action at this time.
0 commit comments