Union Find

Track connected components efficiently with path compression and union by rank.

0 Problems2 hours

Overview

Union-Find (Disjoint Set Union) efficiently tracks which elements belong to the same connected component. With path compression and union by rank, both find and union run in near O(1) amortized time (O(α(n)) — inverse Ackermann).

Complexity Summary

Time Complexity

O(α(n)) ≈ O(1) amortized per operation

Space Complexity

O(n)

Key Patterns & Techniques

Learn the core patterns in this topic. Each block explains when to use the pattern, the intuition behind it, and a compact code example.

1

Find

Concept

returns the root representative of a set

Practice questions for this pattern
2

Union

Concept

merges two sets by connecting their roots

Practice questions for this pattern
3

Path compression

Concept

on find, make all nodes point directly to root

Practice questions for this pattern
4

Union by rank

Concept

attach smaller tree under larger tree to keep height low

Practice questions for this pattern
5

Cycle detection

Concept

if find(u) === find(v) before union, edge (u,v) creates a cycle

Practice questions for this pattern
6

Applications

Concept

number of islands, redundant connections, MST (Kruskal)

Practice questions for this pattern
DSA Practice Online - 150+ Coding Interview Questions | LeetCode Alternative | InstaMock - AI Mock Interview