MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / UnionFind

Class UnionFind

python3/Graphs/connect_the_dots.py:4–28  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2
3
4class UnionFind:
5 def __init__(self, size):
6 self.parent = [i for i in range(size)]
7 self.size = [1] * size
8
9 def union(self, x, y) -> bool:
10 rep_x, rep_y = self.find(x), self.find(y)
11 if rep_x != rep_y:
12 if self.size[rep_x] > self.size[rep_y]:
13 self.parent[rep_y] = rep_x
14 self.size[rep_x] += self.size[rep_y]
15 else:
16 self.parent[rep_x] = rep_y
17 self.size[rep_y] += self.size[rep_x]
18 # Return True if both groups were merged.
19 return True
20 # Return False if the points belong to the same group.
21 return False
22
23
24 def find(self, x) -> int:
25 if x == self.parent[x]:
26 return x
27 self.parent[x] = self.find(self.parent[x])
28 return self.parent[x]
29
30
31def connect_the_dots(points: List[List[int]]) -> int:

Callers 1

connect_the_dotsFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected