Community JavaScript Snippet

The Union-Find With Rank I Copy Into Every Contest

After timing out on a Codeforces 'connected components' problem twice, I memorized this 25-line union-find with path compression and union-by-rank. The find() is iterative (no recursion to blow the stack) and component_count is O(1).

The Union-Find With Rank I Copy Into Every Contest

After timing out on a Codeforces 'connected components' problem twice, I memorized this 25-line union-find with path compression and union-by-rank. The find() is iterative (no recursion to blow the stack) and component_count is O(1).

JavaScript
Frontend
3 snippets
union-find
path-compression
graphs
code-template
emmadiallo

By @emmadiallo

April 30, 2026

·

Updated May 20, 2026

895 views

22

4.3 (11)

The two-pass iterative find is the part I tweak between contests. The first pass walks parent pointers up to the root; the second pass goes back and rewrites every pointer along the path to point directly at the root. This is path compression that flattens the chain so future find calls are O(1). The recursive version is shorter (return parent[x] === x ? x : parent[x] = find(parent[x])) but blows the stack on adversarial chains around a million nodes, which is the contest input size where I started getting WAs. Tracking componentCount and decrementing on a successful union saves you from doing a full Set build at the end of every problem.