Skip to content

Commit a1cdbce

Browse files
refactor(datastructures, union-find): add type hints and doc comments
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent aa47a80 commit a1cdbce

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

datastructures/sets/union_find/__init__.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,29 @@ def get_count(self) -> int:
4646

4747

4848
class 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

0 commit comments

Comments
 (0)