workshop private

← all creations

Lowbit

viz · created 2026-09-24

The Fenwick tree drawn as coverage instead of as a tree — every cell laid out over the exact run of the array it owns, so a prefix query is visibly one run per set bit of k tiling [1..k] with no gap and no overlap, an update is visibly every run that contains i, and three cells-touched counters underneath say why the structure exists at all.

algorithmsinterview-prepcanvas

Every explainer draws the binary indexed tree as a tree: nodes, arrows, i += i & -i written beside them like an incantation. The arrows are not the interesting object. The interesting object is which slice of the array each cell is responsible for, and it is completely determined by one number:

tree[i] = sum of a over (i − lowbit(i), i],    lowbit(i) = i & −i

Cell 13 owns a run of length 1. Cell 12 owns 4. Cell 8 owns 8. Draw those runs at their real positions instead of as a tree, and both algorithms stop being index arithmetic and turn into geometry you can point at.

Four layers, top to bottom:

Query mode. Click a column for prefix(k): the descent k → k − lowbit(k) lights one run per step, each step clearing the lowest set bit, so the number of cells touched is popcount(k) — not “about log n”, exactly the number of ones in the index you asked for. Drag across columns instead and you get a range, drawn as prefix(r) − prefix(l−1): the subtracted runs come up red and paint over the teal in the tiling strip, which is what cancellation looks like.

Update mode. Click a column to add δ to it and the climb i += lowbit(i) lights every run that contains that index, one cell at a time, the stored totals changing as the climb reaches them. The dashed guide line down the column is the reason the set is what it is: those are the only runs the column is inside, so those are the only cells that can be wrong.

The counters are the argument

Three ways to answer “sum of a prefix, with updates”:

queryupdate
plain arrayO(k) scan1 write
prefix-sum array1 readO(n − i) rewrite
Fenwick treepopcount(k)≤ log n

The meters under the demo count cells touched, tallied over everything you do — every click, plus a 200-op batch from run 200 ops with a queries/updates dial. Push the dial to 100% and the prefix-sum array wins by a mile; push it to 0% and the plain array does. Anywhere in between, both of them lose to the structure that is worse than each of them at the thing that one is best at. That is the entire case for the Fenwick tree and it is not an asymptotics claim — it is two bars on a screen, from a workload you chose.

Controls: n is 8, 16 or 32; δ is the update amount (negative is allowed); q/u switch modes, ←/→ move the caret, space applies, r reshuffles the array, w runs a batch.

Reuse

src/lowbit.js is a framework-free ES module, no rendering and no timers:

Gotchas