Trees and graphs · Intermediate

Union-find for connectivity

Track which items are connected as edges arrive: union merges two groups, find names a group, and both are nearly constant time with rank and path compression.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

A disjoint-set forest stores a parent pointer per item; the root of a tree names its group. find follows parents to the root. union links one root under the other. Union by rank (or size) keeps trees shallow, and path compression points every visited node straight at the root.

It answers "are a and b connected?" while edges keep arriving, which BFS or DFS would need to recompute. Kruskal's minimum spanning tree and cycle detection in undirected graphs are the classic uses.

How to recognise it

  • Edges or "same group" facts arrive over time and you must answer connectivity questions in between.
  • Count connected components, or detect whether adding an edge creates a cycle.
  • Grouping equivalent items (accounts, synonyms) by pairwise relations.

When not to use it

  • Edges are removed as well as added: plain union-find cannot split groups.
  • You need the actual path between two nodes, not just whether one exists: use BFS or DFS.
  • The graph is directed and reachability is one-way: union-find models undirected connectivity only.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

parent = [i for i in range(n)]; size = [1] * n
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]   # path halving, a form of compression
        x = parent[x]
    return x
def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb: return false           # already connected: this edge closes a cycle
    if size[ra] < size[rb]: ra, rb = rb, ra
    parent[rb] = ra; size[ra] += size[rb]
    return true
  • Keep a component counter: start at n and subtract one for every successful union.

Complexity

Time O(α(n)) amortized per operation, extra space O(n). α is the inverse Ackermann function, at most 4 for any input that fits in memory. Without union by rank or compression, trees can degenerate into O(n) chains.

Worked examples

Components of 5 nodes after edges (0,1), (3,4), (1,0)

Start with 5 groups. union(0,1) succeeds: 4 groups. union(3,4) succeeds: 3 groups. union(1,0) finds the same root and returns false: that edge would close a cycle. Final groups {0,1}, {2}, {3,4}.

Pitfalls

  • Comparing items instead of their roots in union.
  • Recursive find on deep uncompressed trees overflowing the stack.
  • Forgetting to map arbitrary keys (strings) to dense integer indices first.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.union-find · version 1