Skip to main content

Union-Find (Disjoint Set Union)

A data structure that tracks a set of elements partitioned into disjoint (non-overlapping) subsets.

Core Operations

Where α is the inverse Ackermann function — effectively constant.

Optimizations

  • Path Compression — during find, point every node directly to the root
  • Union by Rank/Size — attach the smaller tree under the root of the larger tree

Implementation

Classic Problems

  • Number of Connected Components
  • Redundant Connection (cycle detection)
  • Accounts Merge
  • Longest Consecutive Sequence
  • Number of Islands (alternative to BFS/DFS)
  • Kruskal’s Minimum Spanning Tree
  • Satisfiability of Equality Equations

When to Use

  • Dynamic connectivity — are two nodes in the same group?
  • Cycle detection in undirected graphs
  • Merging groups or components incrementally
  • Kruskal’s MST algorithm
  • Problems where you need to track connected components over time