s LearnSqueak.com

SMALLTALK LAB

Longest increasing subsequence: keep order, skip values

Build an O(n²) dynamic program in Smalltalk, reconstruct a longest strictly increasing subsequence, and see why gaps make this different from a sliding window.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use a Workspace and Print it for each complete snippet. Each step is independent and declares its own temporary variables. Know Arrays, 1-based indexing, nested loops and blocks. Input values must support consistent < comparisons. A subsequence preserves original order while allowing gaps.

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 - Keep order, allow gaps

A subsequence selects increasing source indices. Its elements need not be adjacent. Strictly increasing means every selected value is less than the next one; do not sort the input first.

Independent Workspace expression - select all, then Print it
| input indices |
input := #(3 1 4 2 5 3 6).
indices := #(2 4 6 7).
indices collect: [:i | input at: i]

Expected: {1. 2. 3. 6.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Keep order, allow gaps
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The indices have gaps, but never move backward. Which two selected values are adjacent in the input?

Download this checkpoint

02 - Find legal predecessors

For a subsequence ending at index i, a predecessor must occur before i and contain a smaller value. Every earlier index is a candidate, not just i-1.

Independent Workspace expression - select all, then Print it
| input i |
input := #(3 1 4 2 5 3 6). i := 5.
((1 to: i-1) select: [:j | (input at: j) < (input at: i)]) asArray

Expected: {1. 2. 3. 4.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Find legal predecessors
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change i to 6. Only indices 2 and 4 qualify: the equal value at index 1 cannot precede 3 in a strict increase.

Download this checkpoint

03 - Compute the best length at each endpoint

Initialize every length to 1 for the singleton subsequence. For each smaller earlier value, try its best length plus one. Earlier answers are final before the current index uses them. The result describes best lengths ending at each position, not prefix maxima.

Independent Workspace expression - select all, then Print it
| input lengths |
input := #(3 1 4 2 5 3 6).
lengths := Array new: input size withAll: 1.
1 to: input size do: [:i |
 1 to: i-1 do: [:j |
  (input at: j) < (input at: i) ifTrue: [
   lengths at: i put: ((lengths at: i) max: (lengths at: j)+1)]]].
lengths

Expected: {1. 1. 2. 2. 3. 3. 4.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Compute the best length at each endpoint
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For #(1 2 3 0), endpoint lengths are #(1 2 3 1). The overall best is 3, not the last entry.

Download this checkpoint

04 - Record links and reconstruct a witness

Whenever a candidate improves a length, store its source index. Remember the endpoint with the largest length, then follow previous links backward. Zero is a sentinel, never an Array index. The solver returns lengths, predecessor indices, selected indices and selected values.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:input | | lengths previous best cursor indices |
 lengths := Array new: input size withAll: 1.
 previous := Array new: input size withAll: 0.
 best := 0.
 1 to: input size do: [:i |
  1 to: i-1 do: [:j |
   ((input at: j) < (input at: i) and: [
    (lengths at: j)+1 > (lengths at: i)]) ifTrue: [
     lengths at: i put: (lengths at: j)+1.
     previous at: i put: j]].
  (best = 0 or: [(lengths at: i) > (lengths at: best)])
   ifTrue: [best := i]].
 indices := OrderedCollection new. cursor := best.
 [cursor > 0] whileTrue: [
  indices addFirst: cursor. cursor := previous at: cursor].
 {lengths. previous. indices asArray.
  (indices collect: [:i | input at: i]) asArray}].
solve value: #(3 1 4 2 5 3 6)

Expected: {{1. 1. 2. 2. 3. 3. 4.}. {0. 0. 1. 2. 3. 4. 5.}. {1. 3. 5. 7.}. {3. 4. 5. 6.}.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Record links and reconstruct a witness
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: There are several longest answers. This scan keeps the first predecessor and first endpoint that attain each best length; it does not promise the lexicographically smallest answer.

Download this checkpoint

05 - Make duplicate handling explicit

The value comparison uses <, so equal values cannot extend each other. The separate > comparison accepts only an improved length. These comparisons have different jobs: strictness and tie-breaking.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:input | | lengths previous best cursor indices |
 lengths := Array new: input size withAll: 1.
 previous := Array new: input size withAll: 0.
 best := 0.
 1 to: input size do: [:i |
  1 to: i-1 do: [:j |
   ((input at: j) < (input at: i) and: [
    (lengths at: j)+1 > (lengths at: i)]) ifTrue: [
     lengths at: i put: (lengths at: j)+1.
     previous at: i put: j]].
  (best = 0 or: [(lengths at: i) > (lengths at: best)])
   ifTrue: [best := i]].
 indices := OrderedCollection new. cursor := best.
 [cursor > 0] whileTrue: [
  indices addFirst: cursor. cursor := previous at: cursor].
 {lengths. previous. indices asArray.
  (indices collect: [:i | input at: i]) asArray}].
{(solve value: #(2 2 2)) fourth.
 (solve value: #(1 2 2 3)) fourth}

Expected: {{2.}. {1. 2. 3.}.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Make duplicate handling explicit
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: To solve the nondecreasing variant, change only the value comparison from < to <=. Then #(2 2 2) has length 3.

Download this checkpoint

06 - Test empty, singleton and descending inputs

An empty input has no endpoint and reconstructs an empty answer. A nonempty descending input has only singleton increasing subsequences. The strict improvement rule chooses its earliest element.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:input | | lengths previous best cursor indices |
 lengths := Array new: input size withAll: 1.
 previous := Array new: input size withAll: 0.
 best := 0.
 1 to: input size do: [:i |
  1 to: i-1 do: [:j |
   ((input at: j) < (input at: i) and: [
    (lengths at: j)+1 > (lengths at: i)]) ifTrue: [
     lengths at: i put: (lengths at: j)+1.
     previous at: i put: j]].
  (best = 0 or: [(lengths at: i) > (lengths at: best)])
   ifTrue: [best := i]].
 indices := OrderedCollection new. cursor := best.
 [cursor > 0] whileTrue: [
  indices addFirst: cursor. cursor := previous at: cursor].
 {lengths. previous. indices asArray.
  (indices collect: [:i | input at: i]) asArray}].
{(solve value: #()) fourth.
 (solve value: #(7)) fourth.
 (solve value: #(9 7 5 3)) fourth}

Expected: {#(). {7.}. {9.}.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Test empty, singleton and descending inputs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: No max operation is sent to an empty collection. Check that the best=0 short-circuit also avoids reading index zero.

Download this checkpoint

07 - Contrast a subsequence with a contiguous run

A sliding window or adjacent-run scan cannot generally solve this problem: it cannot skip a bad element inside its window. Compare the longest adjacent increasing run with our subsequence on the same input.

Independent Workspace expression - select all, then Print it
| solve data run longest |
solve := [:input | | lengths previous best cursor indices |
 lengths := Array new: input size withAll: 1.
 previous := Array new: input size withAll: 0.
 best := 0.
 1 to: input size do: [:i |
  1 to: i-1 do: [:j |
   ((input at: j) < (input at: i) and: [
    (lengths at: j)+1 > (lengths at: i)]) ifTrue: [
     lengths at: i put: (lengths at: j)+1.
     previous at: i put: j]].
  (best = 0 or: [(lengths at: i) > (lengths at: best)])
   ifTrue: [best := i]].
 indices := OrderedCollection new. cursor := best.
 [cursor > 0] whileTrue: [
  indices addFirst: cursor. cursor := previous at: cursor].
 {lengths. previous. indices asArray.
  (indices collect: [:i | input at: i]) asArray}].
data := #(1 2 0 3 4).
run := 1. longest := 1.
2 to: data size do: [:i |
 (data at: i-1) < (data at: i)
  ifTrue: [run := run+1] ifFalse: [run := 1].
 longest := longest max: run].
{longest. (solve value: data) fourth}

Expected: {3. {1. 2. 3. 4.}.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Contrast a subsequence with a contiguous run
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The contiguous run #(0 3 4) has length 3, while skipping zero allows a subsequence of length 4. This short run counter assumes nonempty input.

Download this checkpoint

08 - Assert a reconstructed answer is valid

Test more than the length: selected indices must move forward, values must strictly increase and the witness size must match the known optimum for this case. Comparing indices also distinguishes different occurrences of equal values.

Independent Workspace expression - select all, then Print it
| solve data result selectedIndices values |
solve := [:input | | lengths previous best cursor indices |
 lengths := Array new: input size withAll: 1.
 previous := Array new: input size withAll: 0.
 best := 0.
 1 to: input size do: [:i |
  1 to: i-1 do: [:j |
   ((input at: j) < (input at: i) and: [
    (lengths at: j)+1 > (lengths at: i)]) ifTrue: [
     lengths at: i put: (lengths at: j)+1.
     previous at: i put: j]].
  (best = 0 or: [(lengths at: i) > (lengths at: best)])
   ifTrue: [best := i]].
 indices := OrderedCollection new. cursor := best.
 [cursor > 0] whileTrue: [
  indices addFirst: cursor. cursor := previous at: cursor].
 {lengths. previous. indices asArray.
  (indices collect: [:i | input at: i]) asArray}].
data := #(3 1 4 2 5 3 6).
result := solve value: data.
selectedIndices := result third. values := result fourth.
{selectedIndices size = 4.
 (2 to: selectedIndices size) allSatisfy: [:i |
  (selectedIndices at: i-1) < (selectedIndices at: i)].
 (2 to: values size) allSatisfy: [:i |
  (values at: i-1) < (values at: i)].
 values = (selectedIndices collect: [:i | data at: i])}

Expected: {true. true. true. true.}

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Assert a reconstructed answer is valid
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: These checks verify this example, not all possible inputs. Add increasing, all-equal and negative-valued regression cases.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Longest increasing subsequence: keep order, skip values 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 state at i means the best length ending exactly at i. The overall optimum is the largest state, which may occur before the final input element.

The nested loops inspect n(n-1)/2 pairs: O(n²) time and O(n) auxiliary storage, including predecessor links. An O(n log n) method exists but needs different state and reconstruction machinery.

Sorting destroys the original ordering constraint. A sliding window preserves contiguity, which is a different constraint. Neither is a substitute for this recurrence.

< enforces strict value growth. <= solves a different, nondecreasing problem. Keeping the first equal-length candidate makes the answer deterministic but does not minimize its values.

Three practice challenges

Challenge 1

What are the endpoint lengths and selected values for #(5 1 2 0 3)?

Show solution

Lengths are #(1 1 2 1 3). This solver reconstructs #(1 2 3) using indices #(2 3 5).

Challenge 2

Why is retaining one best subsequence per endpoint enough?

Show solution

Any future extension sees the same final value at that endpoint. A longer subsequence ending there can extend wherever a shorter one could, and gives at least as good a result.

Challenge 3

Adapt the solver to a longest strictly decreasing subsequence. What changes?

Show solution

Change the input comparison from < to >. Keep the length-improvement comparison, traversal order and predecessor reconstruction unchanged.

Continue learning

Knapsack | Edit Distance | Sliding Window

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