union_find
def findRoot(node: int, nodeToParent: dict) -> int:
root = nodeToParent[node]
while root != nodeToParent[root]:
root = nodeToParent[root]
return root
def union(nodeX: int, nodeY: int, nodeToParent: dict) -> bool:
rootX = findRoot(nodeX, nodeToParent)
rootY = findRoot(nodeY, nodeToParent)
if rootX != rootY:
nodeToParent[rootX] = rootY
return True
else:
return False
# use dictionary instead of array to represent the parent mapping
nodeToParent = {x:x for x in range(n)}
# calculate number of components in the graph
numComponents = sum([1 for k,v in nodeToParent.items() if k == v])Reviewed
TODO
Prime Factors
MST
Last updated