Implement a class UnionFind(n) over elements 0 .. n-1, which start in n separate sets:
find(x) -> int: the root ofx's set; two elements share a set exactly when their roots are equal.union(a, b) -> bool: merge the two sets;Trueif they were different,Falseif already together.connected(a, b) -> bool: whetheraandbshare a set.count: an attribute holding the current number of sets.
uf = UnionFind(5)
uf.union(0, 1) # True: merged two sets
uf.union(1, 0) # False: already in the same set
uf.connected(0, 1) # True
uf.connected(0, 2) # False
uf.count # 4
uf.find(1) == uf.find(0) # True
Up to 2 * 10^5 elements.
⭐ Bonus: speed tests with a 200,000-long chain earn a star with path compression (point every node you pass at the root) and union by rank or size. Without them find is O(n) on a chain, and a recursive find hits Python's recursion limit, so write it as a loop.