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).
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.
Kruskal's is the algorithm that put DSU into my permanent toolkit. Sort edges by weight, walk them in order, and add an edge if its endpoints are not already in the same component. The DSU is what makes the connectivity check fast; without it Kruskal's becomes O(E^2) and times out on any non-trivial input. Stopping early when the tree has n - 1 edges is a small but real win on dense graphs: once you have spanned the graph, the remaining edges are guaranteed redundant. The connected flag in the return is how I detect a disconnected input (the MST does not exist; we instead have a minimum spanning forest).
Union-by-size is the variant I prefer when problems ask about component sizes (number of friends, network reach, largest island). It is asymptotically equivalent to union-by-rank but has the convenient side effect of letting me answer componentSize(x) without an extra pass. The weighted DSU is heavier and not always needed, but it solves a class of problems that look like "are these constraints consistent" (e.g., 2-coloring, ratios in a financial graph). I keep three DSU files in my contest snippets folder: this one, the weighted one, and an offline-undo variant for problems that ask about historical states.
