s LearnSqueak.com

ALGORITHMS · RANGE QUERIES

Prefix sums: answer range queries without rescanning

Build running totals in Squeak Smalltalk, answer inclusive range queries with two lookups, and test indexing, invalid bounds and stale cached sums.

13 runnable checkpoints13 exact assertionsNative visual replay

Before you start

Native Squeak 6.1, not a prepared SqueakJS demo. These are independent Workspace expressions, not class definitions. No extra package, network connection or persistent files are required.

  • Use a learning copy of Squeak 6.1. No packages, classes, network access, or external files are required by the examples.
  • Know temporary variables, blocks, Array indexing, and a simple loop. Helpful earlier topics: collections, blocks, and the Workspace.
  • Open a Workspace. Paste one entire checkpoint, including its temporary declaration; select the complete expression and choose Print It. Each checkpoint starts from its own data, so no previous checkpoint needs to have run.
  • If you adapt a checkpoint, give nested block arguments and temporaries names distinct from outer temporaries. Squeak rejects that kind of variable shadowing.
  • Expected outputs use Array notation. Do not paste an expected result back into the selected expression. Use Inspect It if a long nested result is easier to examine there.
  • For the complete verification bundle, open prefix-sums.st as text, copy its entire contents into a Workspace, select all, and choose Print It. It is a Workspace expression, not a class-definition file-in. A successful run should answer 13; a mismatch signals an Error naming the failed checkpoint. The bundle returned 13 in native Squeak 6.1 on 2026-10-25.

Review collections, blocks and the Workspace first. Download the 13-check verification bundle or the complete source and verification kit.

The indexing map

Input positions run from 1 through n. The prefix array has n + 1 positions:

  • prefix at: 1 is 0.
  • prefix at: k + 1 is the sum of input positions 1 through k.
  • The sum from left through right is (prefix at: right + 1) - (prefix at: left).

This is a storage offset, not zero-based Array indexing. Position 0 is never accessed.

NATIVE SQUEAK CAPTURE
Native prefix-sum trace with six input values and seven prefix slots, starting with a zero sentinel
The extra prefix slot holds the total before any values are consumed. Question marks mean not built yet.

Read the position labels, not just the values. Input position 1 and prefix position 1 have different meanings: one contains the first value; the other contains the sum before the first value.

01 · Count the work in a direct range sum

A range query asks for the total between two positions, including both ends. Here, positions 2 through 5 contain -2, 5, 3, and 0. First use a plain loop so there is a simple reference implementation to compare against later. The second result counts the values visited, not elapsed time.

Independent Workspace expression · select all, then Print it
| values total visits |
values := #(6 -2 5 3 0 8).
total := 0.
visits := 0.
2 to: 5 do: [:index |
    total := total + (values at: index).
    visits := visits + 1].
{total. visits}

Expected result (verified in Squeak 6.1):

#(6 4)

A direct query needs one addition per selected value. Repeating long, overlapping queries repeats much of the same work. Prefix sums trade an initial pass and extra storage for cheaper later queries.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 1: Count the work in a direct range sum, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

02 · Build an n + 1 prefix array

Store a zero before any values have been consumed. Squeak arrays start at position 1, so prefix position 1 means “sum of zero values,” position 2 means “sum of the first value,” and position 7 means “sum of all six values.” This one-slot offset is deliberate.

Independent Workspace expression · select all, then Print it
| values prefix |
values := #(6 -2 5 3 0 8).
prefix := Array new: values size + 1.
prefix at: 1 put: 0.
1 to: values size do: [:index |
    prefix at: index + 1
        put: (prefix at: index) + (values at: index)].
prefix

Expected result (verified in Squeak 6.1):

#(0 6 4 9 12 12 20)

The loop invariant is: before iteration index, prefix at: index already contains the sum before that input position. Adding values at: index extends the known total by exactly one value. Negative inputs are fine: a prefix array need not be increasing.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 2: Build an n + 1 prefix array, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

03 · Make every accumulation visible

Each trace row is {input position. input value. previous total. new total}. The trace is a teaching aid, not required storage in the final algorithm.

Independent Workspace expression · select all, then Print it
| values prefix trace previous next |
values := #(6 -2 5 3 0 8).
prefix := Array new: values size + 1.
prefix at: 1 put: 0.
trace := OrderedCollection new.
1 to: values size do: [:index |
    previous := prefix at: index.
    next := previous + (values at: index).
    prefix at: index + 1 put: next.
    trace add: {index. values at: index. previous. next}].
trace asArray

Expected result (verified in Squeak 6.1):

#(#(1 6 0 6) #(2 -2 6 4) #(3 5 4 9) #(4 3 9 12) #(5 0 12 12) #(6 8 12 20))

The zero at input position 5 changes neither total. The negative value at position 2 lowers the total from 6 to 4. Neither case needs a special branch.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 3: Make every accumulation visible, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.
NATIVE SQUEAK CAPTURE
Native prefix-sum trace after consuming 6, minus 2, and 5, storing 9 in prefix position 4
After three values, prefix position 4 contains 9. Negative values work without a special branch.

04 · Subtract the prefix before the range

For inclusive positions left through right, subtract the sum before left from the sum through right. With this storage layout, that is (prefix at: right + 1) - (prefix at: left). Do not use left - 1 as an array index: the sentinel already accounts for the offset.

Independent Workspace expression · select all, then Print it
| build prefix left right throughRight beforeLeft |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
prefix := build value: #(6 -2 5 3 0 8).
left := 2.
right := 5.
throughRight := prefix at: right + 1.
beforeLeft := prefix at: left.
{throughRight. beforeLeft. throughRight - beforeLeft}

Expected result (verified in Squeak 6.1):

#(12 6 6)

The prefixes share all values before left. Subtraction cancels that shared part, leaving only the requested range. This is why addition works here but a minimum-prefix array cannot answer arbitrary range minima by subtraction.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 4: Subtract the prefix before the range, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.
NATIVE SQUEAK CAPTURE
Native range query highlighting input positions 2 through 5 and prefix positions 2 and 6, yielding 12 minus 6 equals 6
The highlighted range contains -2, 5, 3 and 0. Subtract the total before the range from the total through its end.

Replay the construction and subtraction

NATIVE SQUEAK CAPTURE
Native Squeak prefix-sum construction before consuming any values
Eight genuine native Squeak window captures: sentinel, six accumulation states, then the inclusive query. This is a captured-state replay, not mouse footage.

Watch the green prefix slot move one position to the right per input value. At the end, green instead marks the selected input range and the two prefix endpoints. To reproduce a single state in native Squeak, download the visual trace expression, open it as text, and select all → Do it. Change stage := 0. to a number from 0 through 7 before evaluating; close the old window before opening the next state. The fixed drawing needs 1060 × 515 pixels. Close the window to clean up.

05 · Reuse one build for several queries

A block can close over the already-built prefix array. The four queries below cover the full input, an interior range, one value, and a range ending at the final value. The same two array reads and subtraction answer each one.

Independent Workspace expression · select all, then Print it
| build prefix sumFromTo |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
prefix := build value: #(6 -2 5 3 0 8).
sumFromTo := [:left :right |
    (prefix at: right + 1) - (prefix at: left)].
{sumFromTo value: 1 value: 6.
 sumFromTo value: 2 value: 5.
 sumFromTo value: 3 value: 3.
 sumFromTo value: 4 value: 6}

Expected result (verified in Squeak 6.1):

#(20 6 5 11)

The build is linear in the number of values and stores n + 1 totals. Each query performs a constant number of array accesses and arithmetic operations. Those operation counts assume fixed-cost arithmetic; very large Integer operands can cost more, and Float arithmetic can lose precision.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 5: Reuse one build for several queries, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

06 · Reject invalid query bounds deliberately

This query block accepts only nonempty, inclusive ranges with integer bounds inside the original input. It rejects zero, reversed endpoints, an endpoint beyond the input, fractional positions, and every query on an empty input. Validation checks the bounds, not the whole prefix array; the caller must supply an array produced by the build block.

Independent Workspace expression · select all, then Print it
| build query prefix badBounds rejected emptyRejected |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
query := [:prefixTable :startIndex :endIndex |
    (startIndex isInteger and: [endIndex isInteger and: [
        startIndex >= 1 and: [startIndex <= endIndex and: [endIndex < prefixTable size]]]])
        ifFalse: [Error signal: 'Use integer bounds: 1 <= left <= right <= size'].
    (prefixTable at: endIndex + 1) - (prefixTable at: startIndex)].
prefix := build value: #(6 -2 5 3 0 8).
badBounds := #((0 2) (4 3) (1 7) (1 2.5)).
rejected := badBounds collect: [:bounds |
    [query value: prefix value: bounds first value: bounds second.
     false]
        on: Error
        do: [:error | error messageText =
            'Use integer bounds: 1 <= left <= right <= size']].
emptyRejected := [query value: (build value: #()) value: 1 value: 1.
    false]
        on: Error
        do: [:error | error messageText =
            'Use integer bounds: 1 <= left <= right <= size'].
{query value: prefix value: 2 value: 5. rejected. emptyRejected}

Expected result (verified in Squeak 6.1):

#(6 #(true true true true) true)

The exception handlers are only test code. A caller can instead prevent invalid requests before sending them. We do not silently clamp endpoints or reinterpret a reversed range as an empty range, because those policies can hide an indexing mistake.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 6: Reject invalid query bounds deliberately, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

07 · Handle an empty input, zeros, and negative values

Building the prefix array is valid even when there are no values. It produces the one-element sentinel array #(0). No nonempty range exists in that input. An all-zero input produces repeated zero prefixes; negative values may make a later total smaller.

Independent Workspace expression · select all, then Print it
| build |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
{build value: #().
 build value: #(-4 0 9).
 build value: #(0 0 0)}

Expected result (verified in Squeak 6.1):

#(#(0) #(0 -4 -4 5) #(0 0 0 0))

Keep empty-input construction separate from empty-range query policy. A prefix exists for the empty input, but the guarded query from checkpoint 06 correctly refuses to invent a first element.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 7: Handle an empty input, zeros, and negative values, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

08 · Derive an exact range average

Averages need both a sum and a count. Inclusive endpoints select right - left + 1 values. With Integer input, Squeak division can retain an exact Fraction; the final Boolean checks the expected average without depending on how the image prints a Fraction.

Independent Workspace expression · select all, then Print it
| build query prefix left right total count mean |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
query := [:prefixTable :startIndex :endIndex |
    (startIndex isInteger and: [endIndex isInteger and: [
        startIndex >= 1 and: [startIndex <= endIndex and: [endIndex < prefixTable size]]]])
        ifFalse: [Error signal: 'Use integer bounds: 1 <= left <= right <= size'].
    (prefixTable at: endIndex + 1) - (prefixTable at: startIndex)].
prefix := build value: #(6 -2 5 3 0 8).
left := 2.
right := 5.
total := query value: prefix value: left value: right.
count := right - left + 1.
mean := total / count.
{total. count. mean = (3 / 2)}

Expected result (verified in Squeak 6.1):

#(6 4 true)

The average is 3/2, not a rounded 1 or 2. A Float input would instead introduce floating-point rounding. This lesson uses Integers so arithmetic equality tests remain exact.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 8: Derive an exact range average, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

09 · See why an update makes the cache stale

A prefix array is a snapshot of the input totals, not a live view. This example changes one value from -2 to -8 after building. We copy the literal before editing it so the exercise does not mutate a literal held by compiled code.

Independent Workspace expression · select all, then Print it
| build values oldPrefix rebuilt direct |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
values := #(6 -2 5 3 0 8) copy.
oldPrefix := build value: values.
values at: 2 put: -8.
direct := values inject: 0 into: [:total :value | total + value].
rebuilt := build value: values.
{oldPrefix last. direct. rebuilt last}

Expected result (verified in Squeak 6.1):

#(20 14 14)

The old cache is still 20 although the current total is 14. Rebuild after changes, or select a data structure designed for updates, such as a Fenwick tree or segment tree. A prefix array is most useful when many queries share a stable input.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 9: See why an update makes the cache stale, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

10 · Compare every small range with a direct scan

There are 6 + 5 + 4 + 3 + 2 + 1 = 21 nonempty ranges in this six-element input. Check all of them against the simpler direct-sum loop, rather than only the four examples that motivated the implementation.

Independent Workspace expression · select all, then Print it
| build query values prefix checked allMatch direct actual |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
query := [:prefixTable :startIndex :endIndex |
    (startIndex isInteger and: [endIndex isInteger and: [
        startIndex >= 1 and: [startIndex <= endIndex and: [endIndex < prefixTable size]]]])
        ifFalse: [Error signal: 'Use integer bounds: 1 <= left <= right <= size'].
    (prefixTable at: endIndex + 1) - (prefixTable at: startIndex)].
values := #(6 -2 5 3 0 8).
prefix := build value: values.
checked := 0.
allMatch := true.
1 to: values size do: [:left |
    left to: values size do: [:right |
        direct := 0.
        left to: right do: [:index |
            direct := direct + (values at: index)].
        actual := query value: prefix value: left value: right.
        allMatch := allMatch and: [actual = direct].
        checked := checked + 1]].
{checked. allMatch}

Expected result (verified in Squeak 6.1):

#(21 true)

This is an exhaustive check for this particular six-value input, not a proof for every input. The cancellation argument explains why the query works generally; the executable check helps catch a transcription or indexing error.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 10: Compare every small range with a direct scan, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

11 · Exercise: count positive values in a range

Turn each positive value into 1 and everything else into 0, build prefixes of those counts, and ask how many positive values lie between positions 2 and 5. Solve it before reading the code.

Independent Workspace expression · select all, then Print it
| build query values flags prefix |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
query := [:prefixTable :startIndex :endIndex |
    (startIndex isInteger and: [endIndex isInteger and: [
        startIndex >= 1 and: [startIndex <= endIndex and: [endIndex < prefixTable size]]]])
        ifFalse: [Error signal: 'Use integer bounds: 1 <= left <= right <= size'].
    (prefixTable at: endIndex + 1) - (prefixTable at: startIndex)].
values := #(6 -2 5 3 0 8).
flags := values collect: [:value | value > 0 ifTrue: [1] ifFalse: [0]].
prefix := build value: flags.
{flags. query value: prefix value: 2 value: 5}

Expected result (verified in Squeak 6.1):

#(#(1 0 1 1 0 1) 2)

The original input is unchanged. Prefix sums can answer category counts whenever the category can be mapped to a 0-or-1 contribution.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 11: Exercise: count positive values in a range, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

12 · Exercise: compute every width-three total

Use the same prefix array to compute the four consecutive windows of width 3. The last valid start is values size - width + 1. Validate width before entering a general-purpose version of this loop; the exercise supplies a valid width.

Independent Workspace expression · select all, then Print it
| build query values prefix width totals |
build := [:sourceValues |
    | builtPrefix |
    builtPrefix := Array new: sourceValues size + 1.
    builtPrefix at: 1 put: 0.
    1 to: sourceValues size do: [:buildIndex |
        builtPrefix at: buildIndex + 1
            put: (builtPrefix at: buildIndex) + (sourceValues at: buildIndex)].
    builtPrefix].
query := [:prefixTable :startIndex :endIndex |
    (startIndex isInteger and: [endIndex isInteger and: [
        startIndex >= 1 and: [startIndex <= endIndex and: [endIndex < prefixTable size]]]])
        ifFalse: [Error signal: 'Use integer bounds: 1 <= left <= right <= size'].
    (prefixTable at: endIndex + 1) - (prefixTable at: startIndex)].
values := #(6 -2 5 3 0 8).
prefix := build value: values.
width := 3.
totals := OrderedCollection new.
1 to: values size - width + 1 do: [:left |
    totals add: (query value: prefix value: left value: left + width - 1)].
totals asArray

Expected result (verified in Squeak 6.1):

#(9 6 8 11)

This uses one build plus one constant-operation query per window. If fixed-width windows are the only requirement, a rolling total can use less auxiliary storage; the prefix array is more flexible when window widths and endpoints vary.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 12: Exercise: compute every width-three total, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

13 · Exercise: recover the original values

Each original value is the difference between neighboring prefix totals. Recover the input from #(0 6 4 9 12 12 20) without keeping a second copy of the original values.

Independent Workspace expression · select all, then Print it
| prefix recovered |
prefix := #(0 6 4 9 12 12 20).
recovered := Array new: prefix size - 1.
1 to: recovered size do: [:index |
    recovered at: index
        put: (prefix at: index + 1) - (prefix at: index)].
recovered

Expected result (verified in Squeak 6.1):

#(6 -2 5 3 0 8)

Adjacent differences undo the cumulative additions. This relies on the sentinel being the sum before the first value and on every subsequent entry representing exactly one more input value.

NATIVE SQUEAK CAPTURE
Squeak Workspace checkpoint 13: Exercise: recover the original values, with its verified Print it answer
Actual Squeak Workspace after selecting this entire checkpoint and choosing Print it. The highlighted text is the answer.

Cost and limitations

For n values and q queries, the construction performs n additions and uses n + 1 array slots. Querying then uses two lookups and one subtraction per query, giving O(n + q) arithmetic operations and O(n) auxiliary storage under the usual fixed-cost arithmetic model. A direct scan can be preferable for one small query. Rebuilding after each edit loses the advantage when updates are frequent.

The examples intentionally use exact Integers. A Float total can accumulate rounding error, and subtracting nearly equal large totals can lose significant digits. Arbitrary-size integer arithmetic also is not constant-cost in operand size. The build block assumes an indexed sequence of addable numeric values; the guarded query checks only bounds and assumes a trusted prefix array. Do not apply the subtraction identity to operations without a suitable inverse.

Source notes

The examples, data, explanations, and verification bundle in this lesson are original. The separate native execution record confirms that all displayed examples matched their expected values and the complete assertion bundle returned 13 on 2026-10-25.

Continue with binary search or measuring collection work. A prefix sum answers a range total; it is not a search algorithm and does not keep itself synchronized with later edits.