QA
Intermediate LevelData Structures & Algorithms

What is Union-Find (Disjoint Set Union) and how do Path Compression and Union by Rank work?

ā“ Interview Prompt: Explain Union-Find data structure, Find, Union operations, path compression, union by rank, and near-O(1) amortised complexity.

Union-Find (DSU) maintains a collection of disjoint sets and supports:

•
Find(x): Returns the root/representative of x's set.
•
Union(x, y): Merges the sets containing x and y.

Optimisations:

•
Path Compression: During Find, redirect every node directly to the root, flattening the tree.
•
Union by Rank: Attach the shorter tree under the taller one to keep height logarithmic.

Complexity with both optimisations: $O(\alpha(N))$ amortised ā‰ˆ $O(1)$ practically.

Use Cases: Cycle detection, Kruskal's MST, connected components, social network grouping.

Code Implementation Example

typescript
class UnionFind {
  private parent: number[];
  private rank: number[];

  constructor(n: number) {
    this.parent = Array.from({ length: n }, (_, i) => i);
    this.rank = new Array(n).fill(0);
  }

  find(x: number): number {
    if (this.parent[x] !== x)
      this.parent[x] = this.find(this.parent[x]); // path compression
    return this.parent[x];
  }

  union(x: number, y: number): boolean {
    const px = this.find(x), py = this.find(y);
    if (px === py) return false; // already connected — cycle!
    // Union by rank
    if (this.rank[px] < this.rank[py]) this.parent[px] = py;
    else if (this.rank[px] > this.rank[py]) this.parent[py] = px;
    else { this.parent[py] = px; this.rank[px]++; }
    return true;
  }
}
šŸ’”Union-Find with path compression and union by rank — near-O(1) operations.
šŸŽÆ Interview Key Takeaway

Union-Find with path compression + union by rank achieves O(α(N)) amortised — nearly O(1). Essential for Kruskal's MST and cycle detection.

#DSA#Union Find#Disjoint Set#Graph#Intermediate
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?