An interactive, single-file union-find (disjoint set union) that runs entirely in your browser — no backend, no build step.
▶ Live: https://dev48v.github.io/union-find/
Union-Find answers one question fast: are these two things in the same group? — while groups keep merging. It's the quiet workhorse behind Kruskal's MST, cycle detection, connected components, and network connectivity.
- union(a, b) — merge the groups containing
aandb. - find(a) — return the representative (root) of
a's group. - connected(a, b) — just
find(a) === find(b).
Each group is a tree; the root is the representative. Nodes point to their parent, up to the root.
- Union by size — when merging, always hang the smaller tree under the larger root. This keeps trees shallow instead of letting them grow into linked lists.
- Path compression —
findwalks up to the root, then re-points every node on that path directly to the root. In the demo, runfindon a deep node and watch the amber path flatten. The nextfindon any of those nodes is then a single hop.
Together they give α(n) amortized time — the inverse Ackermann function, which is ≤ 4 for any n you'll ever see. Effectively constant.
- union a few pairs and watch separate coloured trees merge into one set.
- Build a deeper tree, then find(x) + compress — the path lights up, then collapses flat.
- connected(a, b) — true only when both roots match; it never needs the path itself.
- Hit random unions to watch components collapse from n down toward 1.
The stats show how many disjoint sets remain and the largest set's size.
It's one file. Open index.html, or:
python -m http.server 8000 # then visit http://localhost:8000MIT © 2026 dev48v — dev48v.infy.uk