Union-Find with path compression.
class UnionFind: def init(self, n): self.parent = list(range(n)) self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px == py:
return
if self.rank[px] < self.rank[py]:
px, py = py, px
self.parent[py] = px
if self.rank[px] == self.rank[py]:
self.rank[px] += 1
def validPath(n, edges, source, destination): uf = UnionFind(n) for u, v in edges: uf.union(u, v) return uf.find(source) == uf.find(destination)
time, space.