MUTABLE DATA · PREFIX SUMS
Fenwick trees: keep prefix sums correct after edits
Build a binary indexed tree in Squeak Smalltalk, update one value without rebuilding every prefix, trace the affected blocks, and verify mixed edits against a direct-sum oracle.
From a snapshot to a repairable index
The prefix-sums lesson ends with a problem: editing an input leaves its cached totals stale. Rebuilding is reasonable for rare changes, but frequent point edits make that full pass expensive. This lesson changes the representation. A Fenwick tree, also called a binary indexed tree, stores overlapping power-of-two blocks in one Array. It repairs only the blocks that contain the edited point, then reconstructs a requested prefix from a few disjoint blocks.
This is not an object tree with child pointers, and it is not a second version of the static prefix-array lesson. Its central operations are add a signed delta at one position and read the current prefix through an endpoint. We will distinguish a delta from a replacement, preserve a block-sum invariant, and compare a long sequence of mutations with an independent model.
Use a learning copy of native Squeak 6.1. Know block arguments, Array indexing and a while loop. Open a Workspace, paste one complete checkpoint, select it and choose Print it. Each of the eight expressions is independent. The longer ones deliberately repeat their helpers; do not concatenate all eight or file the collection in as class definitions. Expected results are not part of the selection.
Download the checkpoint collection, a complete reusable core expression, the full assertion expression, or the native source kit. There are no packages to install and no network requests in the Smalltalk examples.
Choose the indexing and mutation contracts
- Storage: n input values become exactly n tree slots. Both use Squeak’s ordinary indexes 1 through n. There is no stored sentinel at position zero and no extra offset.
- Build: accept an Array of exact Integers, including an empty Array. Build fresh storage. Signed values and zero are allowed; Float and Fraction inputs are outside this deliberately narrow contract.
- Prefix: an integer endpoint k in 0..n means the sum of the first k current values. Prefix zero is zero, including when n is zero. It is a logical empty prefix, not a legal Array access.
- Add: accept an integer position p in 1..n and an integer delta. Increase the represented value by delta. Negative deltas and zero deltas are valid. Invalid requests signal an Error before any write.
- Put: set one represented value to a new Integer by recovering its old value and adding the difference. The source Array is not a second live view.
- Range: accept nonempty inclusive integer bounds 1 ≤ left ≤ right ≤ n. Return prefix(right) − prefix(left − 1). The separate range helper in the core rejects reversed and out-of-bounds ranges.
These are fixed-size trees. Appending a slot, inserting in the middle, deleting a position or changing the meaning of an index requires a different operation or a rebuild. The helpers trust that their table argument is a valid tree made by this code. They do not rescan the entire table for corruption at each call; doing so would defeat their purpose. Keep the Array private in an eventual class.
01 · Give each slot a power-of-two responsibility
A Fenwick slot stores a short block ending at its own index, not always the whole prefix. The lowest set bit of a positive index gives that block length. Squeak sends bitAnd: to the index; negated supplies the other operand.
(1 to: 8) collect: [:index |
| length |
length := index bitAnd: index negated.
{index. length. index - length + 1. index}]Expected: #(#(1 1 1 1) #(2 2 1 2) #(3 1 3 3) #(4 4 1 4) #(5 1 5 5) #(6 2 5 6) #(7 1 7 7) #(8 8 1 8))
Check: Read each row as {slot. block length. first input index. last input index}. Slot 6 covers 5..6; it does not mean the first six values.

For 6, binary 110, 6 bitAnd: 6 negated gives 2. For 8, binary 1000, it gives 8. For odd positive indexes it gives 1. Squeak’s integer bit operations support this identity; these examples do not depend on a machine-word overflow trick. We use it only with positive cursors. At zero it would return zero, so an unguarded update loop could become stuck.
02 · Build the invariant before optimizing the build
Construct each responsibility block by a direct scan. This deliberately simple builder makes the representation visible. It is a reference construction, not the update-based builder we will use later.
| values tree |
values := #(3 1 4 1 5 9 2 6).
tree := (1 to: values size) collect: [:slot |
| first total |
first := slot - (slot bitAnd: slot negated) + 1.
total := 0.
first to: slot do: [:index | total := total + (values at: index)].
total].
treeExpected: #(3 4 4 9 5 14 2 31)
Check: Slot 6 is 5 + 9 = 14; slot 8 is the complete total 31. Odd slots hold one input value.

03 · Read a prefix by removing its final block
For prefix 7, consume slot 7, then 6, then 4. Subtracting the lowest set bit removes the block just read. The checked block accepts zero as the empty prefix without ever accessing array position zero.
| prefix tree walk path |
prefix := [:table :end |
| cursor total |
(end isInteger and: [end between: 0 and: table size])
ifFalse: [Error signal: 'Prefix end must be an integer in 0..size'].
cursor := end. total := 0.
[cursor > 0] whileTrue: [
total := total + (table at: cursor).
cursor := cursor - (cursor bitAnd: cursor negated)].
total].
tree := #(3 4 4 9 5 14 2 31).
walk := 7. path := OrderedCollection new.
[walk > 0] whileTrue: [
path add: walk.
walk := walk - (walk bitAnd: walk negated)].
{path asArray. prefix value: tree value: 7. prefix value: tree value: 0}Expected: {#(7 6 4). 25. 0}
Check: The blocks 7..7, 5..6 and 1..4 are disjoint and cover 1..7 exactly. Three reads produce 2 + 14 + 9 = 25.

04 · Repair only the blocks containing an edited point
Increase input position 3 by six. The update visits slots 3, 4 and 8, adding the same delta to each. Adding the lowest set bit moves upward to the next responsibility block containing that point.
| tree cursor path delta |
tree := #(3 4 4 9 5 14 2 31) copy.
cursor := 3. delta := 6. path := OrderedCollection new.
[cursor <= tree size] whileTrue: [
path add: cursor.
tree at: cursor put: (tree at: cursor) + delta.
cursor := cursor + (cursor bitAnd: cursor negated)].
{path asArray. tree}Expected: {#(3 4 8). #(3 4 10 15 5 14 2 37)}
Check: This is add six, not set to six: the input value changes from 4 to 10. We copy the literal before mutation. A zero starting cursor would never advance, so the reusable block must reject it.

The earlier static prefix array would need to adjust every stored prefix ending at or after position 3. Here only three entries change. Conversely, a query is no longer a single prefix lookup: we deliberately trade constant-operation queries for logarithmic-operation queries and repairs.
Watch read paths and repair paths diverge

First follow the read path 7 → 6 → 4 → 0. The block totals 2, 14 and 9 add to 25. Next follow the repair path 3 → 4 → 8 → 16. Six is added at slots 3, 4 and 8; 16 is beyond the Array and is never accessed. The completed tree answers prefix 7 as 31. A query path and an update path are different traversals of the same storage.
The native drawing computes its initial tree, every traversal step, copied intermediate state and final prefix. During the repair, the row labeled Target shows the desired input while only some affected blocks have been repaired. Those intermediate frames are explanatory, not valid states in which another operation should query the tree. The completed frame is labeled After.
Download the visual expression, open it as text, select all and Do it. Change stage := 0. to an integer from 0 through 7 to open another computed state; close the old window first. It is a fixed 1080 × 650 native Morphic view, not a resizable application. It has no timer, background process, saved data or network dependency. Closing the window is all the cleanup required.
05 · Assemble a checked, mutable tree
Build a fresh zero-filled Array and add each input value through the same checked update operation. The builder copies information into its own storage: later editing the source Array cannot silently change the tree. The source and deltas must be Integers.
| add build prefix values tree before |
add := [:table :position :delta |
| cursor |
(position isInteger and: [position between: 1 and: table size])
ifFalse: [Error signal: 'Update position must be an integer in 1..size'].
delta isInteger ifFalse: [Error signal: 'Delta must be an integer'].
cursor := position.
[cursor <= table size] whileTrue: [
table at: cursor put: (table at: cursor) + delta.
cursor := cursor + (cursor bitAnd: cursor negated)].
table].
build := [:source |
| table |
((source isKindOf: Array) and: [source allSatisfy: [:v | v isInteger]])
ifFalse: [Error signal: 'Build needs an Array of integers'].
table := Array new: source size withAll: 0.
1 to: source size do: [:position |
add value: table value: position value: (source at: position)].
table].
prefix := [:table :end |
| cursor total |
(end isInteger and: [end between: 0 and: table size])
ifFalse: [Error signal: 'Prefix end must be an integer in 0..size'].
cursor := end. total := 0.
[cursor > 0] whileTrue: [
total := total + (table at: cursor).
cursor := cursor - (cursor bitAnd: cursor negated)].
total].
values := #(3 1 4 1 5 9 2 6) copy.
tree := build value: values.
before := prefix value: tree value: 7.
add value: tree value: 3 value: 6.
{before. prefix value: tree value: 7. values at: 3. tree}Expected: {25. 31. 4. #(3 4 10 15 5 14 2 37)}
Check: The tree now represents an edited sequence although the original source still contains 4 at position 3. From here onward send edits through add or put; never change tree slots as if they were input values.

06 · Turn replacement into a delta, then ask a range
To set position 6 to -3, first recover its current value from two adjacent prefixes. Pass new minus old to add. Repeating the same assignment must leave the totals unchanged. The final range calculation subtracts the prefix before its left endpoint.
| add prefix put tree before after rangeTotal |
add := [:table :position :delta |
| cursor |
(position isInteger and: [position between: 1 and: table size])
ifFalse: [Error signal: 'Update position must be an integer in 1..size'].
delta isInteger ifFalse: [Error signal: 'Delta must be an integer'].
cursor := position.
[cursor <= table size] whileTrue: [
table at: cursor put: (table at: cursor) + delta.
cursor := cursor + (cursor bitAnd: cursor negated)].
table].
prefix := [:table :end |
| cursor total |
(end isInteger and: [end between: 0 and: table size])
ifFalse: [Error signal: 'Prefix end must be an integer in 0..size'].
cursor := end. total := 0.
[cursor > 0] whileTrue: [
total := total + (table at: cursor).
cursor := cursor - (cursor bitAnd: cursor negated)].
total].
put := [:table :position :newValue |
| oldValue |
(position isInteger and: [position between: 1 and: table size])
ifFalse: [Error signal: 'Set position must be an integer in 1..size'].
newValue isInteger ifFalse: [Error signal: 'New value must be an integer'].
oldValue := (prefix value: table value: position)
- (prefix value: table value: position - 1).
add value: table value: position value: newValue - oldValue].
tree := #(3 4 4 9 5 14 2 31) copy.
before := prefix value: tree value: 7.
put value: tree value: 6 value: -3.
after := prefix value: tree value: 7.
rangeTotal := (prefix value: tree value: 7) - (prefix value: tree value: 2).
put value: tree value: 6 value: -3.
{before. after. rangeTotal. prefix value: tree value: 7}Expected: #(25 13 9 13)
Check: Replacing 9 by -3 means delta -12, not delta -3. Negative values do not break summation, but they do prevent assuming prefixes are monotone.

The checkpoint supplies the known valid bounds 3..7. A general caller should use the checked range helper from the complete core expression. Its result is independent of whether values are positive, zero or negative. Do not use these signed sums as if they were an increasing cumulative-frequency distribution.
07 · Reject bad updates before touching state
The update block checks its position and delta before its first write. Here four bad requests must raise our intended error and leave the tree unchanged. Prefix zero on an empty tree is valid; updating an empty tree is not.
| add prefix tree saved rejected emptyRejected |
add := [:table :position :delta |
| cursor |
(position isInteger and: [position between: 1 and: table size])
ifFalse: [Error signal: 'Update position must be an integer in 1..size'].
delta isInteger ifFalse: [Error signal: 'Delta must be an integer'].
cursor := position.
[cursor <= table size] whileTrue: [
table at: cursor put: (table at: cursor) + delta.
cursor := cursor + (cursor bitAnd: cursor negated)].
table].
prefix := [:table :end |
| cursor total |
(end isInteger and: [end between: 0 and: table size])
ifFalse: [Error signal: 'Prefix end must be an integer in 0..size'].
cursor := end. total := 0.
[cursor > 0] whileTrue: [
total := total + (table at: cursor).
cursor := cursor - (cursor bitAnd: cursor negated)].
total].
tree := #(3 4 4 9 5 14 2 31) copy. saved := tree copy.
rejected := #((0 1) (9 1) (2.5 1) (2 1.5)) collect: [:request |
[add value: tree value: request first value: request second. false]
on: Error do: [:error |
#('Update position must be an integer in 1..size' 'Delta must be an integer')
includes: error messageText]].
emptyRejected := [add value: #() value: 1 value: 2. false]
on: Error do: [:error |
error messageText = 'Update position must be an integer in 1..size'].
{rejected. tree = saved. prefix value: #() value: 0. emptyRejected}Expected: {#(true true true true). true. 0. true}
Check: Errors are not clamped or silently ignored. The tree parameter itself is trusted to be a valid private Fenwick Array; these guards do not validate arbitrary corrupted tables.

08 · Check every prefix after a mixed edit sequence
Keep an ordinary Array as an independent oracle. Across 21 deterministic signed updates on seven slots, compare all eight prefixes after every edit. Seven is deliberately not a power of two. The scan oracle never uses bit operations.
| add prefix tree values comparisons correct |
add := [:table :position :delta |
| cursor |
(position isInteger and: [position between: 1 and: table size])
ifFalse: [Error signal: 'Update position must be an integer in 1..size'].
delta isInteger ifFalse: [Error signal: 'Delta must be an integer'].
cursor := position.
[cursor <= table size] whileTrue: [
table at: cursor put: (table at: cursor) + delta.
cursor := cursor + (cursor bitAnd: cursor negated)].
table].
prefix := [:table :end |
| cursor total |
(end isInteger and: [end between: 0 and: table size])
ifFalse: [Error signal: 'Prefix end must be an integer in 0..size'].
cursor := end. total := 0.
[cursor > 0] whileTrue: [
total := total + (table at: cursor).
cursor := cursor - (cursor bitAnd: cursor negated)].
total].
tree := Array new: 7 withAll: 0.
values := Array new: 7 withAll: 0.
comparisons := 0. correct := true.
1 to: 21 do: [:turn |
| position delta direct |
position := ((turn * 3) \\ 7) + 1. delta := (turn \\ 5) - 2.
add value: tree value: position value: delta.
values at: position put: (values at: position) + delta.
direct := 0.
0 to: 7 do: [:end |
end > 0 ifTrue: [direct := direct + (values at: end)].
correct := correct and: [(prefix value: tree value: end) = direct].
comparisons := comparisons + 1]].
{correct. comparisons}Expected: #(true 168)
Check: The 168 comparisons include empty prefixes and the final slot after every mutation. A wrong direction, skipped ancestor or mistaken set operation quickly disagrees with this separate model.

Explain why the two directions work
Write lowBit(i) for the lowest set bit of positive i. Our representation invariant is: tree[i] is the sum of current input positions i − lowBit(i) + 1 through i. The tree is a collection of responsibility intervals. A zero-filled tree correctly represents an all-zero sequence; each valid update preserves that interpretation. Checkpoint 2 constructs the intervals directly so we can see exactly what the invariant means before relying on the update code.
Reading removes a disjoint suffix
For a query ending at original k, the loop maintains: total contains the sum of positions cursor + 1 through k; the remaining work is positions 1 through cursor. Initially cursor = k and total = 0. Reading tree[cursor] consumes precisely the interval ending at cursor, then subtracting lowBit(cursor) moves to the position just before that interval. The consumed blocks never overlap and never leave a gap. The positive cursor strictly decreases, so it reaches zero; the remaining prefix is empty and total is the answer.
Updating visits every responsible interval exactly once
Start at the edited position p: its own block contains p, and no earlier slot can cover p because every block ends at its slot. Suppose slot i is a responsible interval. Adding lowBit(i) leads to a larger interval that contains the current interval. The intermediate slots before that next ancestor cover only positions after i, so none can contain p. This enumerates precisely the blocks that must receive the delta. Other blocks exclude p and must not change.
The lowest set bit of the upward cursor moves to a higher bit position after each jump, so the positive cursor grows until it exceeds n. Updating all these block totals by the same delta restores the invariant. While an update is partway through, some blocks are old and others are new; this simple expression is intended for sequential use, not concurrent readers. A class shared between processes would need a separate synchronization policy.
Replacement and ranges follow from the prefix contract
Adjacent prefixes differ by exactly one current value. Therefore oldValue = prefix(p) − prefix(p − 1), and adding newValue − oldValue implements assignment. Two larger prefixes similarly cancel everything before the requested range. This depends on addition having an inverse; replacing addition with minimum does not give the same range-query algorithm.
Count work without inventing a benchmark
A query removes one set bit from its cursor each round. It therefore reads exactly as many tree slots as there are one-bits in its endpoint: prefix 7 reads three slots, prefix 8 only one, and prefix zero none. An update has at most one visited slot per relevant binary level. For n ≥ 1, either path has at most ⌊log₂ n⌋ + 1 visits. Neither path requires the length to be a power of two.
Under a fixed-cost arithmetic model, prefix and add use O(log n) operations and O(1) extra scalar references. Put uses two prefixes and one add, so remains O(log n). An inclusive range uses two prefixes, also O(log n). The tree occupies O(n) slots. The straightforward checked builder in checkpoint 5 performs n additions through the update routine, so its upper bound is O(n log n). This lesson does not claim the O(n) build available in other implementations. The direct responsibility-block builder is a teaching reference, also O(n log n) in the worst case.
Our eight-item example repairs three slots for an edit at position 3, rather than touching all six static prefixes ending at or after that point. This is a count for this example, not a measured speedup. Small inputs and query-heavy workloads with rare edits may favor a plain prefix array. Large Integers also make arithmetic more expensive as operand sizes grow. The trace additionally allocates copies for teaching; it is not the constant-extra-storage operation.
For a fair timing experiment, first make the workload identical: same initial data, same sequence of edits, same queries and same correctness checks. Then follow the native measurement workflow. Do not time the drawing or printing when comparing the data structures themselves.
Verify state, not just one plausible total
The downloadable assertion expression returned 14,277 in native Squeak 6.1, build 23976, on 29 October 2026. These are direct assertions, not a claimed SUnit suite. The runner also separately executed all eight published checkpoints and the complete core expression, then rendered all eight computed visual states from the downloadable visual source.
- All eight checkpoint results are checked exactly, including the checkpoint that performs its own 168 scan comparisons.
- For every size 0 through 17, check the built length, every prefix and every responsibility block against direct sums.
- For each nonempty size, perform 40 alternating additive and replacement edits: 680 mutations overall. After every edit, check every prefix and every block invariant. This covers zero and negative changes, repeated positions, singleton trees and many non-power-of-two sizes.
- After those edits, compare every nonempty inclusive range for each size with a scan: 969 range comparisons.
- Check exact error messages for zero, negative, too-large and noninteger indexes, invalid deltas and replacements, invalid ranges, noninteger build data and empty-tree mutations. Rejected mutations must leave the table equal to its saved copy.
- Check no-op edits, source ownership and large exact Integers that cancel and grow beyond machine-word size.
Open the test source as text, select all and Print it. Expect 14277; a mismatch signals an Error naming the assertion number. Open the independent core expression and Print it to obtain #(19 15). Keep the returned count separate from performance: thousands of passing checks provide evidence, not a timing result or a proof for all possible sequences.
If a test fails, inspect the first wrong block, not only the final total. A wrong sign in the cursor update can leave a query or repair moving in the wrong direction. Using a zero update cursor can loop forever. Passing a new value as a delta silently doubles the old contribution. Writing directly into a tree slot as if it were a source value damages larger responsibility intervals. Forgetting to copy a literal before mutating it changes compiled literal state. Each of these has a different repair; the invariant tells you which one to investigate.
Practice with predictions and explicit contracts
- Predict a boundary path. For a nine-element zero tree, predict the query path for 9 and the update path for position 9. Then repeat for position 1. Hint: keep applying the appropriate sign to lowBit; stop before an illegal access. Expected paths: query 9, 8; update 9 only; update 1, 2, 4, 8.
- Make a correction safely. After checkpoint 5, set position 3 back to 4 using put. Predict prefix 7 before running it: it should return to 25. Explain why adding 4 is the wrong correction.
- Measure visits. Modify copies of add and prefix to return a visit count alongside their useful result. Check endpoints zero, one, a power of two and one less than that power. Compare operation counts before measuring elapsed time.
- Encapsulate the table. Move the five blocks into a class with a private tree instance variable. Expose build, add, put, prefix and range messages; do not return the mutable internal Array. Translate the oracle grid into SUnit and preserve rejection-before-mutation tests.
- Design a faster build separately. Start each slot with one input value; send its accumulated total to its next update ancestor if that ancestor exists. Before using this idea, state why processing indexes in increasing order makes a child’s responsibility block complete. Compare the entire result with checkpoint 2 for every tested size, not just its last slot.
For a different mutable structure, try the binary heap explorer. Both encode structural relationships in Array indexes, but a heap preserves priority ordering while a Fenwick tree preserves interval sums. Neither invariant substitutes for the other.
Primary source and scope
Peter Fenwick, A New Data Structure for Cumulative Probability Tables, Technical Report 88, University of Auckland is the primary source reviewed for this lesson on 29 October 2026. Its cumulative-query and update figures describe binary-index traversals. Its probability-table presentation includes an index-zero entry; our implementation instead uses ordinary one-based Squeak Array slots and a logical empty prefix. We do not implement the report’s frequency-to-symbol search. The report itself flags that separate search procedure as superseded, which is another reason not to copy it into this signed-sum lesson.
The related journal article is A new data structure for cumulative frequency tables, Software: Practice and Experience 24(3), 327–336 (1994). The official Squeak documentation supplies the environment references. This lesson’s Smalltalk blocks, signed mutation workload, assertions, progression, native renderer and explanations are original. The code’s executed contract is narrower than an arbitrary numeric aggregation library.