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

Class UnionFind

python3/Graphs/merging_communities.py:1–27  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class UnionFind:
2 def __init__(self, size: int):
3 self.parent = [i for i in range(size)]
4 self.size = [1] * size
5
6 def union(self, x: int, y: int) -> None:
7 rep_x, rep_y = self.find(x), self.find(y)
8 if rep_x != rep_y:
9 # If 'rep_x' represents a larger community, connect
10 # 'rep_y 's community to it.
11 if self.size[rep_x] > self.size[rep_y]:
12 self.parent[rep_y] = rep_x
13 self.size[rep_x] += self.size[rep_y]
14 # Otherwise, connect 'rep_x's community to 'rep_y'.
15 else:
16 self.parent[rep_x] = rep_y
17 self.size[rep_y] += self.size[rep_x]
18
19 def find(self, x: int) -> int:
20 if x == self.parent[x]:
21 return x
22 # Path compression.
23 self.parent[x] = self.find(self.parent[x])
24 return self.parent[x]
25
26 def get_size(self, x: int) -> int:
27 return self.size[self.find(x)]
28
29
30class MergingCommunities:

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected