SMALLTALK LAB
Find the next greater value with a monotonic stack
Turn a repeated forward scan into a linear pass. Store unresolved positions, resolve them when a greater value arrives, and see why each position enters and leaves the stack only once.
Before you begin
Open a native Squeak Workspace. This lesson uses Arrays and OrderedCollections; positions start at one. Copy one complete checkpoint at a time and choose Print it.
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.
Expected values are Smalltalk expressions. The printer may show explicit Symbol markers: #(A B) and #(#A #B) represent the same array of Symbols.
01 - Define exactly what next means
For each position, find the first strictly greater value to its right, not the largest value anywhere to its right. For 2, the answer is 4 even though 5 appears later. Nil means no matching value exists.
| values |
values := #(2 1 4 3 5).
{values first. values third. values last}Expected: #(2 4 5)

Try it: Draw one arrow from each number to its first greater neighbor on the right.
02 - Build a slow reference scan
A direct search is a useful oracle. Walk right from each position until a greater value appears. Do not replace an already found answer: that would change first greater into last greater.
| values answers |
values := #(2 1 4 3 5).
answers := Array new: values size withAll: nil.
1 to: values size do: [:i |
(i + 1) to: values size do: [:j |
((answers at: i) isNil and: [(values at: j) > (values at: i)])
ifTrue: [answers at: i put: (values at: j)]]].
answersExpected: #(4 4 5 5 nil)

Try it: Count the comparisons for a descending list. Every position scans all remaining positions.
03 - Keep unresolved positions
Store positions rather than values so the answer can be written back into the correct slot. After reading 2 then 1, neither has seen a greater value. Their indices are pending in last-in, first-out order.
| values pending |
values := #(2 1 4 3 5).
pending := OrderedCollection new.
pending addLast: 1; addLast: 2.
{pending asArray. (values at: pending last)}Expected: {#(1 2). 1}

Try it: The stack top contains position 2, whose value is 1. Keep the two concepts distinct.
04 - Resolve a whole suffix at once
When 4 arrives, it answers both 1 and 2. Pop the top index, store 4 there, then repeat while the new top is smaller. Short-circuit and: prevents last from being sent to an empty collection.
| values pending answers i |
values := #(2 1 4 3 5).
pending := OrderedCollection with: 1 with: 2.
answers := Array new: 5 withAll: nil.
i := 3.
[pending notEmpty and: [(values at: pending last) < (values at: i)]]
whileTrue: [answers at: pending removeLast put: (values at: i)].
pending addLast: i.
{answers. pending asArray}Expected: {#(4 4 nil nil nil). #(3)}

Try it: Explain why 4 is the first greater value for both popped positions: no earlier step resolved them.
05 - Run the complete linear pass
Every arriving value resolves all smaller values at the stack top and then waits for its own answer. Pending values remain non-increasing from bottom to top. Unresolved indices keep nil at the end.
| values answers pending |
values := #(2 1 4 3 5).
answers := Array new: values size withAll: nil.
pending := OrderedCollection new.
1 to: values size do: [:i |
[pending notEmpty and: [(values at: pending last) < (values at: i)]]
whileTrue: [answers at: pending removeLast put: (values at: i)].
pending addLast: i].
answersExpected: #(4 4 5 5 nil)

Try it: Trace all five iterations on paper and compare them with the native visual replay below.
06 - Keep equal values waiting
Strictly greater is not greater-or-equal. Equal values must stay on the stack. Both copies of 2 eventually receive 3 as their answer.
| values answers pending |
values := #(2 2 3 3).
answers := Array new: values size withAll: nil.
pending := OrderedCollection new.
1 to: values size do: [:i |
[pending notEmpty and: [(values at: pending last) < (values at: i)]]
whileTrue: [answers at: pending removeLast put: (values at: i)].
pending addLast: i].
answersExpected: #(3 3 nil nil)

Try it: Change < to <= and predict why the first answer would incorrectly become 2.
07 - Handle boundaries without special cases
An empty input produces an empty result. A descending input never pops; a singleton has no value to its right. The loop range and initialized nil slots naturally handle these cases.
| solve |
solve := [:values | | answers pending |
answers := Array new: values size withAll: nil.
pending := OrderedCollection new.
1 to: values size do: [:i |
[pending notEmpty and: [(values at: pending last) < (values at: i)]]
whileTrue: [answers at: pending removeLast put: (values at: i)].
pending addLast: i].
answers].
{solve value: #(). solve value: #(9). solve value: #(3 2 1)}Expected: {#(). #(nil). #(nil nil nil)}

Try it: Try negative numbers. Their ordering works the same way; nil is an absence marker, not zero.
08 - Cross-check every length-four input
Tests are more persuasive when they cover families rather than one happy path. Enumerate all 81 length-four lists over values 1, 2 and 3. Compare the stack algorithm with the direct scan, including equal and descending cases.
| passed |
passed := 0.
1 to: 3 do: [:a | 1 to: 3 do: [:b |
1 to: 3 do: [:c | 1 to: 3 do: [:d | | values fast slow pending |
values := {a. b. c. d}.
fast := Array new: 4 withAll: nil.
slow := Array new: 4 withAll: nil.
pending := OrderedCollection new.
1 to: 4 do: [:i |
[pending notEmpty and: [(values at: pending last) < (values at: i)]]
whileTrue: [fast at: pending removeLast put: (values at: i)].
pending addLast: i.
(i + 1) to: 4 do: [:j |
((slow at: i) isNil and: [(values at: j) > (values at: i)])
ifTrue: [slow at: i put: (values at: j)]]].
fast = slow ifFalse: [self error: 'Cross-check failed'].
passed := passed + 1]]]].
passedExpected: 81

Try it: Extend the generator with a fifth position for 243 cases. A finite test suite supports, but does not replace, a correctness argument.
Watch the computed states

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 invariant is a stack of unresolved indices whose values are non-increasing. A smaller new value cannot answer the top or anything below it; a greater value removes the smaller suffix. Every removed position gets its first valid answer because it survived all earlier positions.
Each index is pushed once and popped at most once. The total number of successful while-loop iterations is at most n, despite the nested syntax. With amortized constant-time OrderedCollection end operations, time is O(n) and auxiliary space is O(n).
Use indices when duplicate values occur. A dictionary keyed by value would merge different positions. This lesson assumes mutually comparable numbers and a finite collection; mixed unrelated object types need an explicit comparison policy.
Three practice challenges
Return a distance
How many positions away is the next greater value?
Show solution
When popping index old, store i - old instead of values at: i. Preserve nil for no answer. The sample becomes #(2 1 2 1 nil).
Next smaller
Find the first strictly smaller value to the right.
Show solution
Reverse the comparison from < to >. Keep all other stack operations. The sample #(2 1 4 3 5) produces #(1 nil 3 nil nil).
Count stack operations
Instrument pushes and pops on a descending and an increasing list.
Show solution
Increment pushes after addLast: and pops inside whileTrue:. Pushes equal n. Descending data has zero pops; increasing data has n - 1. This is an operation count, not an elapsed-time benchmark.
Continue learning
Stacks Queues | Sliding Window | Sorting Visualiser
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.