s LearnSqueak.com

SMALLTALK LAB

Segment trees: range minima that survive point updates

Build an inspectable minimum tree, cover inclusive ranges with disjoint nodes, and repair ancestors after edits, with native Smalltalk checkpoints and computed Morphic states.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Each checkpoint is independent: paste its entire expression, including temporary variables, select all and choose Print it. Familiarity with Arrays, blocks and one-based indexes helps. This lesson complements prefix sums and Fenwick trees: its operation is minimum, which has no subtraction inverse, and updates may increase or decrease a value.

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 - Ask a minimum question, not a sum question

Our six readings are indexed from one. The minimum from positions 2 through 5 is 2. A prefix sum can subtract two totals, but subtracting two prefix minima cannot recover an arbitrary range minimum. We need a different summary structure.

Independent Workspace expression - select all, then Print it
| readings |
readings := #(8 3 7 9 2 6).
{(readings copyFrom: 2 to: 5) min. (readings copyFrom: 3 to: 4) min}

Expected: #(2 7)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Ask a minimum question, not a sum question
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The second range excludes both 3 and 2, so its minimum rises to 7. All ranges in this lesson include both endpoints.

Download this checkpoint

02 - Pad to a complete tree without inventing infinity

Choose the smallest power of two at least as large as the data. Leaves start at index base. Six readings need eight slots; nil marks the two unused leaves. It is absence, not a large numeric sentinel.

Independent Workspace expression - select all, then Print it
| values base tree |
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
{base. tree copyFrom: base to: tree size}

Expected: #(8 #(8 3 7 9 2 6 nil nil))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Pad to a complete tree without inventing infinity
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Leaf index base + i - 1 represents data index i. A data index and a tree index are different quantities.

Download this checkpoint

03 - Give missing children a neutral meaning

The combine block returns the smaller of two real values. If one child is absent, keep the other. This allows padding without assuming a maximum reading. Nil is reserved for absence and cannot be a reading.

Independent Workspace expression - select all, then Print it
| combine |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
{combine value: 9 value: 2. combine value: nil value: 6.
 combine value: 6 value: nil. combine value: nil value: nil}

Expected: #(2 6 6 nil)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Give missing children a neutral meaning
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try negative numbers. The neutral nil policy works without modifying a guessed infinity constant.

Download this checkpoint

04 - Build summaries from the bottom upward

Children of tree index i are 2*i and 2*i+1. Descending through the internal indexes guarantees both children are ready before the parent is computed. The root summarizes every real reading.

Independent Workspace expression - select all, then Print it
| values base tree combine |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
(base - 1) to: 1 by: -1 do: [:i |
 tree at: i put: (combine value: (tree at: i * 2)
  value: (tree at: i * 2 + 1))].
tree

Expected: #(2 3 2 3 7 2 nil 8 3 7 9 2 6 nil nil)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Build summaries from the bottom upward
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Check node 5: it summarizes original positions 3 and 4, whose minimum is 7. Node 7 has no real leaves and stays nil.

Download this checkpoint

05 - Cover one range with disjoint summaries

For the range 2 through 5, the tree supplies leaf 9 (position 2), node 5 (positions 3 and 4), and leaf 12 (position 5). Their blocks do not overlap and include no outside element. Combining their summaries gives the answer.

Independent Workspace expression - select all, then Print it
| values base tree combine result |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
(base - 1) to: 1 by: -1 do: [:i |
 tree at: i put: (combine value: (tree at: i * 2)
  value: (tree at: i * 2 + 1))].
result := nil.
#(9 5 12) do: [:i | result := combine value: result value: (tree at: i)].
{(#(9 5 12) collect: [:i | tree at: i]). result}

Expected: #(#(3 7 2) 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Cover one range with disjoint summaries
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Drawing the covered leaf positions is a useful check: 2, then 3..4, then 5. The algorithm must never include position 1 just because its sibling is needed.

Download this checkpoint

06 - Find those blocks with a boundary walk

Move both inclusive boundaries from leaves toward the root. An odd left index is a right child whose left sibling lies outside the range, so consume it before moving upward. An even right index is a left child whose right sibling lies outside. Consume it too. The remaining boundaries then enclose complete sibling pairs.

Independent Workspace expression - select all, then Print it
| values base tree combine query |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
(base - 1) to: 1 by: -1 do: [:i |
 tree at: i put: (combine value: (tree at: i * 2)
  value: (tree at: i * 2 + 1))].
query := [:lo :hi | | left right answer |
 ((lo isInteger and: [hi isInteger]) and:
  [(lo between: 1 and: values size) and: [hi between: lo and: values size]])
   ifFalse: [Error signal: 'Use a nonempty inclusive range inside the data'].
 left := base + lo - 1. right := base + hi - 1. answer := nil.
 [left <= right] whileTrue: [
  left odd ifTrue: [answer := combine value: answer value: (tree at: left).
   left := left + 1].
  right even ifTrue: [answer := combine value: answer value: (tree at: right).
   right := right - 1].
  left := left // 2. right := right // 2].
 answer].
{query value: 2 value: 5. query value: 3 value: 4.
 query value: 1 value: 6. query value: 6 value: 6}

Expected: #(2 7 2 6)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Find those blocks with a boundary walk
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The guards reject empty, reversed and out-of-bounds ranges. The loop processes only a constant number of nodes at each tree level.

Download this checkpoint

07 - Update one leaf and repair its ancestors

Replace reading 5 with 10. The old minimum 2 disappears, so the new overall minimum is 3. Recompute each ancestor from both children, even when a value increases. The original values Array is only the construction fixture; after updates, the tree is the current data source.

Independent Workspace expression - select all, then Print it
| values base tree combine query update |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
(base - 1) to: 1 by: -1 do: [:i |
 tree at: i put: (combine value: (tree at: i * 2)
  value: (tree at: i * 2 + 1))].
query := [:lo :hi | | left right answer |
 ((lo isInteger and: [hi isInteger]) and:
  [(lo between: 1 and: values size) and: [hi between: lo and: values size]])
   ifFalse: [Error signal: 'Use a nonempty inclusive range inside the data'].
 left := base + lo - 1. right := base + hi - 1. answer := nil.
 [left <= right] whileTrue: [
  left odd ifTrue: [answer := combine value: answer value: (tree at: left).
   left := left + 1].
  right even ifTrue: [answer := combine value: answer value: (tree at: right).
   right := right - 1].
  left := left // 2. right := right // 2].
 answer].
update := [:index :value | | position |
 (index isInteger and: [index between: 1 and: values size])
  ifFalse: [Error signal: 'Update index is outside the data'].
 value isNumber ifFalse: [Error signal: 'Use a numeric value'].
 position := base + index - 1. tree at: position put: value.
 [position > 1] whileTrue: [
  position := position // 2.
  tree at: position put: (combine value: (tree at: position * 2)
   value: (tree at: position * 2 + 1))].
 value].
update value: 5 value: 10.
{query value: 1 value: 6. query value: 3 value: 6.
 tree at: base + 5 - 1. values at: 5}

Expected: #(3 6 10 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Update one leaf and repair its ancestors
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: A min-only update such as parent := parent min: newValue is wrong for increases: it would leave the removed 2 behind. Read the tree leaf if you need the current value.

Download this checkpoint

08 - Cross-check every valid range after two edits

A separate Array serves as a slow reference. Update two tree leaves, including a negative reading, then compare all 21 nonempty ranges with direct slicing. Also confirm that reversed ranges and invalid update indexes raise the intended errors.

Independent Workspace expression - select all, then Print it
| values base tree combine query update |
combine := [:a :b | a isNil ifTrue: [b] ifFalse: [b isNil ifTrue: [a] ifFalse: [a min: b]]].
values := #(8 3 7 9 2 6).
base := 1. [base < values size] whileTrue: [base := base * 2].
tree := Array new: (base * 2 - 1).
values withIndexDo: [:value :i | tree at: base + i - 1 put: value].
(base - 1) to: 1 by: -1 do: [:i |
 tree at: i put: (combine value: (tree at: i * 2)
  value: (tree at: i * 2 + 1))].
query := [:lo :hi | | left right answer |
 ((lo isInteger and: [hi isInteger]) and:
  [(lo between: 1 and: values size) and: [hi between: lo and: values size]])
   ifFalse: [Error signal: 'Use a nonempty inclusive range inside the data'].
 left := base + lo - 1. right := base + hi - 1. answer := nil.
 [left <= right] whileTrue: [
  left odd ifTrue: [answer := combine value: answer value: (tree at: left).
   left := left + 1].
  right even ifTrue: [answer := combine value: answer value: (tree at: right).
   right := right - 1].
  left := left // 2. right := right // 2].
 answer].
update := [:index :value | | position |
 (index isInteger and: [index between: 1 and: values size])
  ifFalse: [Error signal: 'Update index is outside the data'].
 value isNumber ifFalse: [Error signal: 'Use a numeric value'].
 position := base + index - 1. tree at: position put: value.
 [position > 1] whileTrue: [
  position := position // 2.
  tree at: position put: (combine value: (tree at: position * 2)
   value: (tree at: position * 2 + 1))].
 value].
update value: 5 value: 10. update value: 2 value: -4.
{((1 to: 6) allSatisfy: [:lo |
 (lo to: 6) allSatisfy: [:hi |
  (query value: lo value: hi) = ((#(8 -4 7 9 10 6) copyFrom: lo to: hi) min)]]).
 ([query value: 4 value: 3. false] on: Error do: [:error |
  error messageText = 'Use a nonempty inclusive range inside the data']).
 ([update value: 0 value: 5. false] on: Error do: [:error |
  error messageText = 'Update index is outside the data'])}

Expected: #(true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Cross-check every valid range after two edits
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the edited values and the reference Array together. Try restoring the minimum or setting several equal minima, and verify all ranges again.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Segment trees: range minima that survive point updates 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

The construction assumes a nonempty Array of finite, mutually comparable real numbers; examples use integers. Nil is exclusively padding. The update block checks isNumber as a basic guard, not a full real-number or NaN validator. Do not pass complex numbers or incomparable objects to min:.

With n readings and base the next power of two, the tree stores 2*base-1 slots. Because base is less than 2*n for n>0, storage and construction are O(n). Each inclusive query and each point update takes O(log n).

The query boundary walk depends on the one-based heap layout with leaves starting at base. Copying parity conditions from a zero-based tree without adjusting them gives subtle wrong answers. The independent all-ranges check catches many such errors.

Minimum is associative, and nil acts as an identity here. Unlike sum, minimum has no inverse: two prefix minima cannot generally recover a range minimum. This implementation handles point edits, not range edits; range-update lazy propagation is a separate technique.

After construction, values retains the original fixture and its size. Updates modify only tree. Keeping a second mutable current-data Array is possible, but then every edit must update both representations consistently.

Three practice challenges

Challenge 1: increase the old winner

After step 7, query positions 4 through 6. What is the answer, and which reading wins?

Show solution

The current readings there are 9, 10 and 6, so the answer is 6 at position 6. Recomputing ancestors from both children is what removes the obsolete 2.

Challenge 2: support a maximum tree

Which pieces change if you want range maxima instead?

Show solution

Replace a min: b by a max: b in combine, retain the nil identity, and update the slow reference and expectations. Build, query boundaries and point-update traversal stay the same because maximum is associative too.

Challenge 3: explain a one-element input

Use values := #(42). What are base, tree and the range 1..1 result?

Show solution

Base is 1 and the one-slot tree is #(42). There are no internal nodes to build. Query 1..1 consumes the root leaf and returns 42. Updating index 1 changes that slot with no ancestor loop.

Continue learning

Fenwick Tree | Prefix Sums | Search Tree

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