Union-Find — also called a Disjoint Set Union, or DSU — is a data structure that keeps a collection of elements split into non-overlapping groups and answers two questions fast: are these two elements in the same group? and merge the groups these two belong to. It is the workhorse behind connectivity queries, cycle detection in graphs, and Kruskal's minimum-spanning-tree algorithm. You will build it as a factory: unionFind(n) creates a structure over the n elements 0..n-1, each starting in its own one-element set, and returns an object with find, union, connected, and count. See the disjoint-set data structure for background.
unionFind(n) // create a structure over elements 0..n-1, each in its own set
// returns:
// find(x) -> the representative (root) of x's set
// union(x, y) -> merge x's and y's sets; true if they were separate
// connected(x, y) -> are x and y in the same set?
// count() -> how many disjoint sets remain right now
const uf = unionFind(5); // {0} {1} {2} {3} {4} — five singleton sets
uf.count(); // 5
uf.connected(0, 2); // false — different sets
uf.union(0, 1); // true — joined {0} and {1} into {0,1}
uf.union(1, 2); // true — now {0,1,2}
uf.connected(0, 2); // true — 0 and 2 are transitively connected
uf.union(0, 2); // false — already in the same set
uf.count(); // 3 — {0,1,2} {3} {4}
0..n-1 — n integer-indexed elements, each starting in its own singleton set.find returns the same root for both.true when the two elements were in different sets (now joined) and false when they were already together.n and drops by one on each successful union; a redundant union or a self-union leaves it unchanged.union and find run in amortized O(α(n)); α is the inverse Ackermann function, which is at most 4 for any n you will ever use.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.