progress

~/problems / Weighted graphs / Union-Find

Union-Find class with component count

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Implement a class UnionFind(n) over elements 0 .. n-1, which start in n separate sets:

  • find(x) -> int: the root of x's set; two elements share a set exactly when their roots are equal.
  • union(a, b) -> bool: merge the two sets; True if they were different, False if already together.
  • connected(a, b) -> bool: whether a and b share 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.

Topic: Union-Find. Path compression + union by rank; connectivity and grouping.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc