Union-Find (Disjoint Set Union)

💡Strategies for Solving This Problem

Understanding Union-Find

Union-Find (also called Disjoint Set Union or DSU) is a data structure that efficiently tracks elements partitioned into disjoint sets. It supports two operations: find (which set does element belong to?) and union (merge two sets).

When to Use Union-Find

  • Connectivity: Check if two nodes are connected
  • Cycle detection: In undirected graphs
  • Grouping: Merge elements into groups dynamically
  • Kruskal's MST: Minimum spanning tree algorithm
  • Network connectivity: Are all computers connected?

Core Operations

1. Find(x): Which set does x belong to?

  • Returns representative (root) of x's set
  • Used to check if two elements in same set

2. Union(x, y): Merge sets containing x and y

  • Connect roots of two trees
  • Make one root point to the other

Key Optimizations

1. Path Compression (Find)

When finding root, make all nodes on path point directly to root. Flattens tree structure.

Before:  A -> B -> C -> D (root)
After:   A -> D, B -> D, C -> D

2. Union by Rank/Size

Always attach smaller tree under root of larger tree. Keeps trees balanced.

Time Complexity

  • Without optimizations: O(n) per operation (worst case)
  • With path compression only: O(log n) amortized
  • With both optimizations: O(α(n)) ≈ O(1) where α is inverse Ackermann function

Note: α(n) grows so slowly that it's effectively constant for any practical n.

Common Interview Problems

  • Number of Connected Components (LeetCode 323): Count disjoint sets
  • Graph Valid Tree (LeetCode 261): Check if graph is tree using Union-Find
  • Redundant Connection (LeetCode 684): Find edge that creates cycle
  • Accounts Merge (LeetCode 721): Group accounts by email
  • Satisfiability of Equality Equations (LeetCode 990): Check consistency
  • Number of Islands II (LeetCode 305): Dynamic connectivity

Asked at: Google, Facebook, Amazon, Microsoft, Bloomberg

Scroll to Top