workshop private

← all creations

Flatten

viz · created 2026-09-25

Disjoint-set union drawn as the trees themselves, with every root on the top line so a node's row is literally what finding it costs — union by rank refusing to build the tall tree, and path compression re-parenting a whole walked path on the way back, so the structure gets flatter by being used.

algorithmsinterview-prepcanvas

Every explainer for union-find draws the parent array. The array is the implementation. The idea is a forest, and the idea worth having is that find is not a read — it is a write. It walks a path to the root, and on the way back it re-points every node it passed at the root, so the query pays for its own future. A data structure that gets faster because you used it is rare enough to be worth watching happen rather than reading about.

So the piece draws the trees. Every root sits on the top line, which means a node’s row is its depth, and its depth is exactly what finding it costs — one horizontal line across the whole picture is one price. Everything else follows from that one decision.

The default sequence is union(i, i-1) for i = 1..n, which is what a loop over sorted edges does and looks entirely innocent. With union by rank off it builds a linked list wearing a tree’s clothes: n = 16 gives a staircase 15 deep, Σ depth 120, and every find on the far end costs 15 hops. Turn rank on and the same sequence produces a star of depth 1, because each new singleton has rank 0 and rank refuses to hang the taller tree off the shorter one.

The other preset is the doubling order — pair up, then pair the pairs — which is the tallest a rank-union forest can be made: every union is a tie, so rank has to break it and the height climbs by one per doubling. Thirty-two nodes, five levels, and that is the worst case rather than an unlucky one.

Three things the picture is built to make visible:

Presets are the union order and n (8 / 16 / 32). u unions a random pair, q runs a storm of twelve finds, f finds the currently deepest node, c and k flip compression and rank, r resets.

Reuse

src/dsu.js is a framework-free ES module. Every mutating call returns a trace instead of a bare answer, because the interesting part of union-find is the path it walked and what it did to that path:

No rendering, no timers, no DOM. The canvas demo is reference code.

Gotchas