Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Data Structures
Data Structureshard

What problem does Union-Find (Disjoint Set Union) solve?

Tags
#union-find#dsu#kruskal#connectivity
Back to categoryPractice quiz

Answer

Union-Find maintains disjoint sets with find(x) (representative) and union(a,b) (merge). It’s used for connectivity and Kruskal’s MST; with path compression + union by rank, operations are almost O(1) amortized.

class DSU {
  private parent: number[];

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

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

  union(a: number, b: number) {
    const ra = this.find(a);
    const rb = this.find(b);
    if (ra !== rb) this.parent[rb] = ra;
  }
}

Advanced answer

Deep dive

Union-Find (Disjoint Set Union) maintains a partition of elements into disjoint sets and supports:

  • find(x): return the representative of x’s set
  • union(a, b): merge two sets

With two optimizations:

  • path compression (flatten trees during find)
  • union by rank/size (attach smaller tree under larger)

…each operation is effectively constant for real inputs: O(alpha(n)) amortized (inverse Ackermann, grows extremely slowly).

Where it’s used

  • Connectivity queries in an undirected graph: are u and v connected?
  • Kruskal’s MST: union edges as you pick them, detect cycles via find.
  • Grouping / clustering problems (merge-by-constraint).

Examples

class DSU {
  private parent: number[]
  private size: number[]

  constructor(n: number) {
    this.parent = Array.from({ length: n }, (_, i) => i)
    this.size = Array.from({ length: n }, () => 1)
  }

  find(x: number): number {
    if (this.parent[x] === x) return x
    this.parent[x] = this.find(this.parent[x])
    return this.parent[x]
  }

  union(a: number, b: number) {
    let ra = this.find(a)
    let rb = this.find(b)
    if (ra === rb) return
    if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra]
    this.parent[rb] = ra
    this.size[ra] += this.size[rb]
  }
}

Common pitfalls

  • Forgetting union by rank/size (can degrade performance).

Related questions

Algorithms
Kruskal vs Prim: what is the main difference and typical data structures?
#mst#kruskal#prim
Algorithms
Kruskal vs Prim for MST — how do they differ?
#mst#kruskal#prim
  • Using DSU for directed connectivity (it’s not the same problem).
  • Confusing amortized complexity with per-operation worst-case guarantees.