Union-Find, also called Disjoint Set Union (DSU), is a data structure for tracking connected components.
It supports two key operations:
find(x): return representative (root) ofx's componentunion(a, b): merge components containingaandb
With path compression and union by size or rank, both operations are almost constant time in practice.
DSU implementation (TypeScript)
export 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) {
this.parent[x] = this.find(this.parent[x]!); // path compression
}
return this.parent[x]!;
}
union(a: number, b: number): boolean {
let rootA = this.find(a);
let rootB = this.find(b);
if (rootA === rootB) return false;
if (this.size[rootA]! < this.size[rootB]!) {
[rootA, rootB] = [rootB, rootA];
}
this.parent[rootB] = rootA;
this.size[rootA]! += this.size[rootB]!;
return true;
}
connected(a: number, b: number): boolean {
return this.find(a) === this.find(b);
}
}
Pattern 1: Cycle detection in undirected graph
If an edge connects two nodes already in same component, a cycle exists.
export function hasCycle(n: number, edges: Array<[number, number]>): boolean {
const dsu = new DSU(n);
for (const [u, v] of edges) {
if (!dsu.union(u, v)) return true;
}
return false;
}
Pattern 2: Count connected components
Union all edges, then count unique roots.
export function countComponents(n: number, edges: Array<[number, number]>): number {
const dsu = new DSU(n);
for (const [u, v] of edges) dsu.union(u, v);
const roots = new Set<number>();
for (let i = 0; i < n; i++) roots.add(dsu.find(i));
return roots.size;
}
Pattern 3: Kruskal's algorithm (MST)
Sort edges by weight; add edge if it joins different components.
export function kruskalMST(
n: number,
edges: Array<[number, number, number]>, // [u, v, weight]
): number {
edges.sort((a, b) => a[2] - b[2]);
const dsu = new DSU(n);
let total = 0;
let used = 0;
for (const [u, v, w] of edges) {
if (!dsu.union(u, v)) continue;
total += w;
used++;
if (used === n - 1) break;
}
return used === n - 1 ? total : -1;
}
When DSU is the right choice
- Repeated connectivity checks with edge additions
- Grouping entities by relation
- Detecting redundant connections
- Building MST with Kruskal
If the graph is static and you only need one traversal, DFS or BFS may be simpler.
Common mistakes
- Forgetting path compression
- Union without size or rank (can degrade performance)
- Using DSU for directed cycle detection (not valid in general)
- Not normalizing node labels when input is 1-based
Practice set
- Number of connected components in undirected graph
- Redundant connection
- Accounts merge
- Number of provinces
- Kruskal MST variations
DSU is one of the highest ROI interview tools. Code is short, reusable, and solves many graph-connectivity problems.
