Blog

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

© 2025 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;
  }
}

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