s LearnSqueak.com

SMALLTALK LAB

Longest common subsequence: build a table and recover the match

Compare two sequences without requiring adjacent matches. Build a prefix-length table, reconstruct one optimal answer, test edge cases and reduce memory with two rolling rows in Squeak.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Open a Workspace in native Squeak 6.1. Select one complete checkpoint and choose Print it. Every checkpoint is independent and uses only standard collections and blocks. Expected values are literal Smalltalk expressions; printed collection formatting may vary. Use Strings first, then try Arrays of comparable elements. The visual replay fills one real DP row per stage, from the empty border to the completed table.

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, but allow gaps

A subsequence keeps the relative order of selected elements; it need not occupy adjacent positions. This greedy membership checker advances only when the next wanted character appears. It decides whether a supplied candidate fits, not whether it is longest. Empty text is a subsequence of every text.

Independent Workspace expression - select all, then Print it
| isSubsequence |
isSubsequence := [:candidate :text | | next |
 next := 1.
 text do: [:letter |
  (next <= candidate size and: [
   (candidate at: next) = letter])
    ifTrue: [next := next + 1]].
 next > candidate size].
{isSubsequence value: 'ACD' value: 'ABCD'.
 isSubsequence value: 'ACD' value: 'BACD'.
 isSubsequence value: 'DA' value: 'ABCD'.
 isSubsequence value: '' value: 'ABCD'}

Expected: #(true true false true)

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

Try it: ACD is common to ABCD and BACD, but is not a substring of ABCD because B interrupts it. DA fails because the order is reversed. Try AAD against ABCD: one A cannot be reused.

Download this checkpoint

02 - Reserve a border for empty prefixes

Define D(i,j) as the LCS length of the first i characters on the left and the first j on the right. Any empty prefix has length zero. Smalltalk Arrays start at one, so D(i,j) lives at row i+1, column j+1. Allocate each row separately, or updating one row could accidentally update every row.

Independent Workspace expression - select all, then Print it
| left right table |
left := 'ABCD'. right := 'BACD'.
table := (1 to: left size + 1) collect: [:unused |
 Array new: right size + 1 withAll: 0].
{table size. table first size.
 table first. table last.
 table first == table last}

Expected: #(5 5 #(0 0 0 0 0) #(0 0 0 0 0) false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Reserve a border for empty prefixes
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: A four-by-four character comparison needs a five-by-five table. The extra row and column let the recurrence read neighbors without special cases inside the loop.

Download this checkpoint

03 - Compute one row from three neighbors

When the final characters match, extend the diagonal prefix answer by one. Otherwise the optimal subsequence must omit at least one of those final characters: take the larger of the upper and left neighbors. Filling left to right makes all dependencies available. For the first left character A, the row becomes one at the right prefix BA and stays one.

Independent Workspace expression - select all, then Print it
| left right table i |
left := 'ABCD'. right := 'BACD'.
table := (1 to: left size + 1) collect: [:unused |
 Array new: right size + 1 withAll: 0].
i := 1.
1 to: right size do: [:j |
 (table at: i + 1) at: j + 1 put:
  ((left at: i) = (right at: j)
   ifTrue: [((table at: i) at: j) + 1]
   ifFalse: [((table at: i) at: j + 1)
    max: ((table at: i + 1) at: j)])].
table at: 2

Expected: #(0 0 1 1 1)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Compute one row from three neighbors
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Read the entries as comparisons with empty, B, BA, BAC and BACD. At A versus A, the diagonal is zero and the result is one. A mismatch does not reset an LCS cell to zero; that would be a different, substring algorithm.

Download this checkpoint

04 - Fill every prefix and test awkward inputs

The nested loops evaluate each non-border cell once. The bottom-right cell answers the whole-input question. This block accepts indexable sequences with equality-comparable elements, not only Strings. These checks include empty, disjoint, repeated, identical, and numeric inputs; repeated symbols are counted by position.

Independent Workspace expression - select all, then Print it
| length |
length := [:left :right | | table |
 table := (1 to: left size + 1) collect: [:unused |
  Array new: right size + 1 withAll: 0].
 1 to: left size do: [:i |
  1 to: right size do: [:j |
   (table at: i + 1) at: j + 1 put:
    ((left at: i) = (right at: j)
     ifTrue: [((table at: i) at: j) + 1]
     ifFalse: [((table at: i) at: j + 1)
      max: ((table at: i + 1) at: j)])]].
 (table last) last].
{length value: 'ABCD' value: 'BACD'.
 length value: '' value: 'ABC'.
 length value: 'ABC' value: ''.
 length value: 'ABC' value: 'xyz'.
 length value: 'AAAA' value: 'AA'.
 length value: 'ABC' value: 'ABC'.
 length value: #(1 2 1 3) value: #(1 1 3)}

Expected: #(3 0 0 0 2 3 3)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Fill every prefix and test awkward inputs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change ABCD/BACD to ABC/BAC: the length is two, but both AC and BC qualify. The length table does not yet tell you which witness to return. Comparisons here are case-sensitive.

Download this checkpoint

05 - Backtrack one answer with a fixed tie rule

Start at the full prefixes. Equal characters belong to the chosen answer: collect that character and move diagonally. At a mismatch, follow the larger neighboring value. On equality move up, dropping the left input character; this deterministic rule returns AC rather than BC for ABC/BAC. It does not promise the alphabetically smallest LCS in general. Backtracking collects characters in reverse order.

Independent Workspace expression - select all, then Print it
| left right table rowIndex columnIndex reversed |
left := 'ABC'. right := 'BAC'.
 table := (1 to: left size + 1) collect: [:unused |
  Array new: right size + 1 withAll: 0].
 1 to: left size do: [:i |
  1 to: right size do: [:j |
   (table at: i + 1) at: j + 1 put:
    ((left at: i) = (right at: j)
     ifTrue: [((table at: i) at: j) + 1]
     ifFalse: [((table at: i) at: j + 1)
      max: ((table at: i + 1) at: j)])]].
rowIndex := left size. columnIndex := right size.
reversed := OrderedCollection new.
[rowIndex > 0 and: [columnIndex > 0]] whileTrue: [
 (left at: rowIndex) = (right at: columnIndex)
  ifTrue: [reversed add: (left at: rowIndex).
   rowIndex := rowIndex - 1. columnIndex := columnIndex - 1]
  ifFalse: [((table at: rowIndex) at: columnIndex + 1) >=
    ((table at: rowIndex + 1) at: columnIndex)
   ifTrue: [rowIndex := rowIndex - 1]
   ifFalse: [columnIndex := columnIndex - 1]]].
String withAll: reversed reversed

Expected: 'AC'

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Backtrack one answer with a fixed tie rule
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Replace >= by > to prefer moving left on a tie: the same fixture then returns BC. With empty or disjoint Strings the result is the empty String. Both tie policies preserve the optimal length.

Download this checkpoint

06 - Cross-check with a tiny exhaustive oracle

A separate approach enumerates every subset of left-input positions, then retains those whose characters occur in order on the right. A bit selects a position; iteration in increasing position order preserves order. This deliberately exponential oracle is useful only for small fixtures, but gives a test independent of the dynamic-programming recurrence.

Independent Workspace expression - select all, then Print it
| left right best winners |
left := 'ABC'. right := 'BAC'.
best := 0. winners := Set new.
0 to: (1 bitShift: left size) - 1 do: [:mask |
 | candidate next |
 candidate := String streamContents: [:stream |
  1 to: left size do: [:position |
   (mask bitAt: position) = 1
    ifTrue: [stream nextPut: (left at: position)]]].
 next := 1.
 right do: [:letter |
  (next <= candidate size and: [
   (candidate at: next) = letter])
    ifTrue: [next := next + 1]].
 next > candidate size ifTrue: [
  candidate size > best ifTrue: [
   best := candidate size. winners removeAll].
  candidate size = best ifTrue: [winners add: candidate]]].
{best. winners asSortedCollection asArray}

Expected: #(2 #('AC' 'BC'))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Cross-check with a tiny exhaustive oracle
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The Set removes duplicate Strings produced by different subsets when letters repeat. Do not replace the polynomial algorithm with this search for large inputs: there are 2 raised to m masks.

Download this checkpoint

07 - Save space when only the length matters

Each new row depends only on the previous row and the partially filled current row. Replacing the entire table with two rows keeps the same O(mn) time but uses O(n) auxiliary storage, where n is the right input length. Allocate a fresh current row each round. This version deliberately discards information needed for the simple backtracking procedure.

Independent Workspace expression - select all, then Print it
| length |
length := [:left :right | | previous current |
 previous := Array new: right size + 1 withAll: 0.
 left do: [:letter |
  current := Array new: right size + 1 withAll: 0.
  1 to: right size do: [:j |
   current at: j + 1 put:
    (letter = (right at: j)
     ifTrue: [(previous at: j) + 1]
     ifFalse: [(previous at: j + 1)
      max: (current at: j)])].
  previous := current].
 previous last].
{length value: 'ABCD' value: 'BACD'.
 length value: '' value: 'ABC'.
 length value: 'AAA' value: 'AA'.
 length value: 'ABC' value: ''}

Expected: #(3 0 2 0)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Save space when only the length matters
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Put the shorter sequence on the right to reduce storage to O(min(m,n)); the answer is symmetric. Assigning current := previous would alias the same Array and overwrite needed diagonal values.

Download this checkpoint

08 - Relate LCS to insertion-and-deletion distance

If an LCS has length k, keep those k characters, delete the other m-k left characters, then insert the n-k missing right characters. Thus minimum insertion-plus-deletion cost is m+n-2k when each operation costs one. This is not ordinary Levenshtein distance when substitution is allowed at cost one. Longest increasing subsequence is also different: it orders values within one sequence rather than matching two sequences.

Independent Workspace expression - select all, then Print it
| length source target common |
length := [:left :right | | table |
 table := (1 to: left size + 1) collect: [:unused |
  Array new: right size + 1 withAll: 0].
 1 to: left size do: [:i |
  1 to: right size do: [:j |
   (table at: i + 1) at: j + 1 put:
    ((left at: i) = (right at: j)
     ifTrue: [((table at: i) at: j) + 1]
     ifFalse: [((table at: i) at: j + 1)
      max: ((table at: i + 1) at: j)])]].
 (table last) last].
source := 'CAT'. target := 'CUT'.
common := length value: source value: target.
{common. source size + target size - (2 * common).
 length value: target value: source}

Expected: #(2 2 2)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Relate LCS to insertion-and-deletion distance
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: CT is an LCS. Delete A and insert U for a cost of two; a unit-cost substitution would cost only one. Symmetry is a useful length-test property even though a deterministic tie rule can choose different witnesses when inputs are swapped.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Longest common subsequence: build a table and recover the match 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

D(i,j) describes prefix lengths, not character indexes. Its physical location is (table at: i+1) at: j+1. The upper neighbor is row i, column j+1; left is row i+1, column j; diagonal is row i, column j.

On a match D(i,j)=D(i-1,j-1)+1. On a mismatch D(i,j)=max(D(i-1,j),D(i,j-1)). These are LCS recurrences. A longest-common-substring algorithm would reset a mismatch to zero and track a maximum anywhere in the table.

Allocate independent row Arrays. Array new: rows withAll: aRow repeats the same mutable row reference. Mutating one shared row corrupts all apparent rows.

For lengths m and n, the full table takes O(mn) cell updates and O(mn) auxiliary storage, assuming constant-time indexing and equality. Including the empty borders, the precise allocated size is (m+1)(n+1). Empty inputs require only initialization. Backtracking makes at most m+n moves.

One LCS is not necessarily unique. The up-on-ties rule is reproducible, not a lexicographic guarantee. Counting all optimal paths is not the same as counting distinct resulting Strings, especially with repeated symbols.

Two rolling rows preserve lengths but not the full path for this backtracking method. A linear-space reconstruction needs a different approach, such as divide-and-conquer; do not claim the simple two-row version returns a witness.

Characters are compared exactly with =. Case folding, word tokenization and punctuation handling are separate input decisions. For numeric sequences, use Array withAll: reversed reversed instead of String withAll: to reconstruct a numeric answer.

Three practice challenges

Read the completed grid

Fill the full table for ABCD and BACD. What are its five rows, including the empty-prefix border, and what answer does the up-on-ties backtracker select?

Show solution

The rows are #(0 0 0 0 0), #(0 0 1 1 1), #(0 1 1 1 1), #(0 1 1 2 2), and #(0 1 1 2 3). The final length is 3. The checkpoint 5 backtracker with these inputs returns ACD; BCD is another valid LCS.

Test repeated symbols

Predict the length for AABA versus ABAA. Give one common subsequence of that length and explain why four is impossible.

Show solution

The length is 3. AAA and ABA are both valid witnesses. A length-four subsequence of a four-character String must use every position, so it would require AABA and ABAA to be identical. They are not. The fixed up-on-ties reconstruction returns AAA.

Find the smallest rolling-row footprint

You need only the LCS length of sequences of lengths 20 and 10,000. Which sequence should be on the right, how many values do two rows hold, and how many non-border DP updates occur?

Show solution

Put the length-20 sequence on the right. Each row contains 21 values including the empty prefix, so the two live rows hold 42 values. There are 20*10,000 = 200,000 non-border updates. Swapping inputs changes the storage requirement, not the mathematical LCS length.

Continue learning

Edit Distance | Longest Increasing Subsequence | Knapsack

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