All Patterns

Union Find

Track connected components efficiently with union and find operations, using path compression and rank optimization.

When to use

  • Connected components
  • Cycle detection in undirected graphs
  • Kruskal's MST
  • Dynamic connectivity

When NOT to use

  • Need shortest paths
  • Directed graphs (use other methods)
  • Need to split components

Common traps

  • Forgetting path compression
  • Not using union by rank
  • Confusing with BFS/DFS connectivity

Key Invariant

Find with path compression + union by rank gives nearly O(1) amortized operations

Problems (9)

#128Number of Connected Components
medium
#129Redundant Connection
medium
#130Accounts Merge
medium
#131Most Stones Removed
medium
#133Number of Provinces
medium
#134Satisfiability of Equality Equations
medium
#135Smallest String With Swaps
medium
#282Number of Operations to Make Network Connected
medium
#283Redundant Connection II
hard