s LearnSqueak.com

SMALLTALK LAB

Sliding windows: find the best fixed-length run

Find the highest-sum consecutive block by removing one outgoing reading and adding one incoming reading, then verify every result against a direct scan.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a learning copy of native Squeak 6.1. Open a Workspace, paste one complete checkpoint, select it and choose Print it. Each checkpoint is independent; the expected result is not part of the selection. You should know Arrays, block arguments and simple loops. Unlike the prefix-sums and Fenwick lessons, this is one sequential scan of a fixed-width window, using constant auxiliary state for the winning pair. It does not build a reusable range-query table. The examples use exact Integers; a checked block returns {maximumSum. earliestStartIndex}.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Define a window before finding the winner

A window is a consecutive group with a fixed width. With seven readings and width three, the legal starts are 1 through 5. A reading cannot be skipped just because it is negative. This checkpoint copies the first three readings only so we can name the object we are trying to score; later steps avoid making copies for every window.

Independent Workspace expression - select all, then Print it
| values width starts |
values := #(2 -1 3 4 -2 5 1).
width := 3.
starts := 1 to: values size - width + 1.
{starts asArray. values copyFrom: 1 to: width}

Expected: #(#(1 2 3 4 5) #(2 -1 3))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Define a window before finding the winner
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: There are size - width + 1 windows, not size windows. Which start would reach past index 7?

Download this checkpoint

02 - Build an independent scanning reference

First compute every total in the most direct way: start at each legal position and sum exactly three readings. This repeats work, but it is easy to inspect and becomes our reference for checking the faster algorithm. The largest total is seven, from positions 4 through 6.

Independent Workspace expression - select all, then Print it
| values width totals |
values := #(2 -1 3 4 -2 5 1). width := 3.
totals := (1 to: values size - width + 1) collect: [:start |
 | total |
 total := 0.
 start to: start + width - 1 do: [:i |
  total := total + (values at: i)].
 total].
totals

Expected: #(4 6 5 7 4)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Build an independent scanning reference
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Add the values at positions 4, 5 and 6 by hand: 4 + (-2) + 5.

Download this checkpoint

03 - Slide once: remove one, add one

Moving from the first window to the second preserves the middle two readings. Only 2 leaves and 4 enters, so 4 - 2 + 4 gives 6. Subtract the outgoing value itself, including its sign; do not subtract its absolute value. No prefix array or new window copy is needed.

Independent Workspace expression - select all, then Print it
| values total outgoing incoming |
values := #(2 -1 3 4 -2 5 1).
total := 4.
outgoing := values at: 1.
incoming := values at: 4.
total := total - outgoing + incoming.
{outgoing. incoming. total}

Expected: #(2 4 6)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Slide once: remove one, add one
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: On the next slide, -1 leaves and -2 enters. The next total is 6 - (-1) + (-2) = 5.

Download this checkpoint

04 - Record every slide with one running sum

Compute the first total once. For each later start, the outgoing index is start - 1 and the incoming index is start + width - 1. The trace records start, outgoing reading, incoming reading and resulting total. It is a debugging aid; a production maximum-only scan does not need to retain the trace.

Independent Workspace expression - select all, then Print it
| values width total trace |
values := #(2 -1 3 4 -2 5 1). width := 3.
total := 0. trace := OrderedCollection new.
1 to: width do: [:i | total := total + (values at: i)].
2 to: values size - width + 1 do: [:start |
 | outgoing incoming |
 outgoing := values at: start - 1.
 incoming := values at: start + width - 1.
 total := total - outgoing + incoming.
 trace add: {start. outgoing. incoming. total}].
trace asArray

Expected: #(#(2 2 4 6) #(3 -1 -2 5) #(4 3 5 7) #(5 4 1 4))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Record every slide with one running sum
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For each row, verify that the incoming index is exactly width positions after the outgoing index.

Download this checkpoint

05 - Remember the best total and its location

Keep only the current total and the best pair found so far. Initialize the best total from the first real window, not from zero: an all-negative input still has a winning window. Use strictly greater-than to keep the earliest winner when two totals tie. Return the start index as well as the sum, so callers can recover the actual readings.

Independent Workspace expression - select all, then Print it
| values width total best bestStart |
values := #(2 -1 3 4 -2 5 1). width := 3.
total := 0.
1 to: width do: [:i | total := total + (values at: i)].
best := total. bestStart := 1.
2 to: values size - width + 1 do: [:start |
 total := total - (values at: start - 1)
                + (values at: start + width - 1).
 total > best ifTrue: [best := total. bestStart := start]].
{best. bestStart. values copyFrom: bestStart to: bestStart + width - 1}

Expected: #(7 4 #(4 -2 5))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Remember the best total and its location
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change > to >= and try #(1 1 1) with width 2. Which tied window wins now?

Download this checkpoint

06 - Make the operation reusable with a checked contract

Wrap the scan in a two-argument block. This teaching version accepts an Array of Integers and an Integer width from 1 through the array size. Empty input, zero width, fractional widths and overlarge widths signal an Error before indexing. The supplied Array is read only. Integer arithmetic stays exact; floating-point drift is deliberately outside this version.

Independent Workspace expression - select all, then Print it
| bestWindow |
bestWindow := [:values :width |
 | total best bestStart |
 (values isArray and: [values allSatisfy: [:each | each isInteger]])
  ifFalse: [Error signal: 'Use an Array of Integers'].
 (width isInteger and: [width >= 1 and: [width <= values size]])
  ifFalse: [Error signal: 'Width must be in 1..size'].
 total := 0.
 1 to: width do: [:i | total := total + (values at: i)].
 best := total. bestStart := 1.
 2 to: values size - width + 1 do: [:start |
  total := total - (values at: start - 1)
                 + (values at: start + width - 1).
  total > best ifTrue: [best := total. bestStart := start]].
 {best. bestStart}].
{
 bestWindow value: #(2 -1 3 4 -2 5 1) value: 3.
 bestWindow value: #(-8 -3 -6 -2) value: 2.
 bestWindow value: #(5 5 5) value: 2
}

Expected: #(#(7 4) #(-8 3) #(10 1))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Make the operation reusable with a checked contract
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The negative example chooses -6 + -2, not an imaginary empty window worth zero.

Download this checkpoint

07 - Check boundary sizes and rejection

Width one chooses the largest single reading. Width equal to the whole array produces one window and no slide iterations. Also exercise failures explicitly; a test that never calls an invalid width cannot tell us whether the guard works. Catch Error only around the intentional bad call, so a genuine problem in the valid cases is not hidden.

Independent Workspace expression - select all, then Print it
| bestWindow rejected |
bestWindow := [:values :width |
 | total best bestStart |
 (values isArray and: [values allSatisfy: [:each | each isInteger]])
  ifFalse: [Error signal: 'Use an Array of Integers'].
 (width isInteger and: [width >= 1 and: [width <= values size]])
  ifFalse: [Error signal: 'Width must be in 1..size'].
 total := 0.
 1 to: width do: [:i | total := total + (values at: i)].
 best := total. bestStart := 1.
 2 to: values size - width + 1 do: [:start |
  total := total - (values at: start - 1)
                 + (values at: start + width - 1).
  total > best ifTrue: [best := total. bestStart := start]].
 {best. bestStart}].
rejected := [bestWindow value: #(4 1) value: 0. false]
 on: Error do: [:error | error messageText = 'Width must be in 1..size'].
{bestWindow value: #(4 -1 7) value: 1.
 bestWindow value: #(4 -1 7) value: 3.
 rejected}

Expected: #(#(7 3) #(10 1) true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Check boundary sizes and rejection
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try an empty Array, width 4 for three readings, and width 1.5. They must fail instead of reading an invalid index.

Download this checkpoint

08 - Compare all widths with a separate reference

This final check constructs 100 deterministic inputs with positive, negative and repeated readings. For every valid width it independently rescans each window and uses the same earliest-tie contract. It also checks that the input was not mutated and that every invalid width raises the expected error. True means all comparisons passed; no timing or speed claim is inferred from this test.

Independent Workspace expression - select all, then Print it
| bestWindow assert inputValues before expected scanTotal actual |
bestWindow := [:values :width |
 | total best bestStart |
 (values isArray and: [values allSatisfy: [:each | each isInteger]])
  ifFalse: [Error signal: 'Use an Array of Integers'].
 (width isInteger and: [width >= 1 and: [width <= values size]])
  ifFalse: [Error signal: 'Width must be in 1..size'].
 total := 0.
 1 to: width do: [:i | total := total + (values at: i)].
 best := total. bestStart := 1.
 2 to: values size - width + 1 do: [:start |
  total := total - (values at: start - 1)
                 + (values at: start + width - 1).
  total > best ifTrue: [best := total. bestStart := start]].
 {best. bestStart}].
assert := [:ok | ok ifFalse: [Error signal: 'Sliding window check failed']].
1 to: 10 do: [:size |
 1 to: 10 do: [:seed |
  inputValues := (1 to: size) collect: [:i | ((i * seed) \\ 11) - 5].
  before := inputValues copy.
  1 to: size do: [:width |
   expected := nil.
   1 to: size - width + 1 do: [:start |
    scanTotal := 0.
    start to: start + width - 1 do: [:i | scanTotal := scanTotal + (inputValues at: i)].
    (expected isNil or: [scanTotal > expected first])
     ifTrue: [expected := {scanTotal. start}]].
   actual := bestWindow value: inputValues value: width.
   assert value: (actual = expected)].
  assert value: (inputValues = before)]].
#(0 -1 4 1.5) do: [:bad |
 assert value: ([bestWindow value: #(1 2 3) value: bad. false]
  on: Error do: [:e | e messageText = 'Width must be in 1..size'])].
assert value: ([bestWindow value: #() value: 1. false]
 on: Error do: [:e | e messageText = 'Width must be in 1..size']).
assert value: ([bestWindow value: #(1 2.5) value: 1. false]
 on: Error do: [:e | e messageText = 'Use an Array of Integers']).
true

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Compare all widths with a separate reference
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Keep the direct reference simple. Reusing the sliding formula inside both implementations could repeat the same mistake.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Sliding windows: find the best fixed-length run native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

Do not initialize best to zero. For all-negative readings that would return a result that no legal window achieves.

Do not confuse highest-sum window with the largest individual item in every window. The latter problem needs a different algorithm.

Keep width fixed throughout a scan. Variable-width problems, and editing previous readings during the scan, require a different contract.

The main scan performs width additions initially and two arithmetic updates per remaining window: O(n) arithmetic operations, compared with O((n-width+1)*width) for rescanning. Exact big Integer arithmetic is not constant-cost for arbitrarily large values.

Trace collections and copied slices are teaching tools. Excluding the input and returned pair, the maximum-only block holds O(1) auxiliary state. It returns indexes into the unchanged input, not a live view.

This lesson is native-only; the existing browser playground remains available for other prepared demos.

Three practice challenges

Prefer the last tied window

Change the winning-window contract to prefer the greatest start index when totals tie.

Show solution

Replace total > best with total >= best. For #(5 5 5) at width 2, expect #(10 2). Update the independent reference to use >= too, and retain a specific tie test.

Return a mean without losing exactness

For the winning window, return its arithmetic mean as a third field.

Show solution

Inside the reusable block, return {best. bestStart. best / width}. For #(2 -1 3 4 -2 5 1) at width 3, expect #(7 4 (7/3)) conceptually; check the result using {7. 4. 7/3}, an evaluated array. Since every candidate has the same positive width, the maximum-sum window is also the maximum-mean window.

Recover the winning readings

Call the block and copy the winning slice without changing the input.

Show solution

Store the returned pair in answer. Use values copyFrom: answer second to: answer second + width - 1. For the main sample, this gives #(4 -2 5). The copy is useful for display but costs O(width) extra space.

Continue learning

Prefix Sums | Fenwick Tree | Collections | Blocks | Testing

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Windows.