sagelearnai

Union-Find

Signal: "are these two connected?", number of connected components, merging groups (accounts, friend circles), detecting a cycle in an undirected graph, or connectivity that changes as edges are added over time.

Core idea: keep a forest where each set is a tree identified by its root. find(x) walks to the root; union(a, b) attaches one root under the other. Two optimizations make both operations nearly O(1), specifically O(α(n)), where α is the inverse Ackermann function and is at most 4 for any realistic n:

  • Path compression: during find, point nodes directly at the root.
  • Union by rank/size: attach the smaller tree under the larger one.
before find(4) 1 2 4 path compression after 1 2 4
python
class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                 # already connected → this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True

Union-Find vs BFS/DFS: for a static graph, either works. Union-Find shines when edges arrive incrementally and you need connectivity answers along the way, or when you just need to know whether an edge creates a cycle.

Problems

  1. Number of Connected Components in an Undirected Graph (Medium): Start with n components; each successful union reduces the count by 1
  2. Number of Provinces (Medium): Count successful unions; components = n − unions
  3. Redundant Connection (Medium): The first edge whose endpoints are already connected
  4. Accounts Merge (Medium): Union all emails within each account; group emails by root; sort each group
  5. Most Stones Removed with Same Row or Column (Medium): Answer = stones − components; union each stone's row with its column
  6. Satisfiability of Equality Equations (Medium): Union all "==" first; then every "!=" must join different sets
  7. Number of Operations to Make Network Connected (Medium): Need n−1 cables at least; answer = components − 1
  8. Smallest String With Swaps (Medium): Swappable indices form components; sort characters within each component
  9. Evaluate Division (Medium): Weighted Union-Find: weight[x] = x / root(x); a/b = weight[a] / weight[b]
  10. Redundant Connection II (Hard): Cases: a node with two parents and/or a cycle; skip the second parent-edge and test with Union-Find