s LearnSqueak.com

SMALLTALK LAB

Palindrome tables: find the longest mirrored substring

Build a dynamic program for contiguous palindromes in Squeak, recover the earliest longest match, test every small binary string against a brute-force oracle, and compare expansion around centers.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 Workspace and Print it on each complete expression. Each checkpoint is independent and uses only the standard image. Strings are compared as exact Squeak Characters; no case folding, Unicode normalization or grapheme-cluster handling is implied. Use Do it for the separate five-stage Morphic board.

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 - Ask for a contiguous palindrome

A palindrome reads the same forward and backward. A substring occupies consecutive positions; a subsequence may skip positions. We compare Characters exactly, including case and spaces. In BANANA the longest palindromic substring is ANANA at positions 2 through 6.

Independent Workspace expression - select all, then Print it
| text fragment |
text := 'BANANA'. fragment := text copyFrom: 2 to: 6.
{fragment. fragment = fragment reversed.
 'Racecar' = 'Racecar' reversed.
 'racecar' = 'racecar' reversed}

Expected: #('ANANA' true false true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Ask for a contiguous palindrome
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try a space or uppercase letter. If you normalize text first, positions refer to that normalized text, not automatically to the original.

Download this checkpoint

02 - Lay down the smallest intervals

Let table[i][j] mean that positions i through j form a palindrome. One-character intervals are always true. A two-character interval is true exactly when its characters match. Allocate a fresh row for each i: sharing one mutable row would corrupt the table.

Independent Workspace expression - select all, then Print it
| text n table |
text := 'ABBA'. n := text size.
table := (1 to: n) collect: [:row | Array new: n withAll: false].
1 to: n do: [:i | (table at: i) at: i put: true].
1 to: n - 1 do: [:i |
 (table at: i) at: i + 1 put: ((text at: i) = (text at: i + 1))].
{(table at: 1) at: 1. (table at: 2) at: 3.
 (table at: 1) at: 2. (table at: 1) == (table at: 2)}

Expected: #(true true false false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Lay down the smallest intervals
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Change ABBA to ABCA. The two middle characters no longer form a palindrome.

Download this checkpoint

03 - Grow from shorter intervals to longer ones

For length at least three, the endpoints must match AND the interior must already be a palindrome. Visit intervals by increasing length, so the length-minus-two interior is known. The lazy or: keeps length-one and length-two cases from looking outside the table.

Independent Workspace expression - select all, then Print it
| text n table finish palindrome |
text := 'BANANA'. n := text size.
table := (1 to: n) collect: [:row | Array new: n withAll: false].
1 to: n do: [:length |
 1 to: n - length + 1 do: [:start |
  finish := start + length - 1.
  palindrome := (text at: start) = (text at: finish)
   and: [length <= 2 or: [(table at: start + 1) at: finish - 1]].
  (table at: start) at: finish put: palindrome]].
{(table at: 2) at: 4. (table at: 2) at: 6.
 (table at: 1) at: 6. (table at: 3) at: 5}

Expected: #(true true false true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Grow from shorter intervals to longer ones
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Run the length loop downward and reason about why it fails: interiors start false and have not yet been computed.

Download this checkpoint

04 - Keep a start and length, then copy once

Keep only the location of the best result while filling the table. Replace the best only for a strictly longer palindrome. Starts are visited from left to right within a length, so equal-length ties keep the earliest start. Return start, length and the substring; empty input uses start zero as a sentinel.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:input |
 | n table bestStart bestLength finish palindrome |
 n := input size. bestStart := 0. bestLength := 0.
 table := (1 to: n) collect: [:row | Array new: n withAll: false].
 1 to: n do: [:length |
  1 to: n - length + 1 do: [:start |
   finish := start + length - 1.
   palindrome := (input at: start) = (input at: finish)
    and: [length <= 2 or: [(table at: start + 1) at: finish - 1]].
   (table at: start) at: finish put: palindrome.
   (palindrome and: [length > bestLength]) ifTrue: [
    bestStart := start. bestLength := length]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
solve value: 'BANANA'

Expected: #(2 5 'ANANA')

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Keep a start and length, then copy once
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try ABBA, then add one character at each end. The algorithm copies the winning substring only after completing the table.

Download this checkpoint

05 - Test empty input and deliberate ties

The empty string has no valid character position, so its answer is start zero, length zero and empty text. Every nonempty string has at least a one-character palindrome. BABAD has two length-three choices; the documented earliest-start rule selects BAB.

Independent Workspace expression - select all, then Print it
| solve |
solve := [:input |
 | n table bestStart bestLength finish palindrome |
 n := input size. bestStart := 0. bestLength := 0.
 table := (1 to: n) collect: [:row | Array new: n withAll: false].
 1 to: n do: [:length |
  1 to: n - length + 1 do: [:start |
   finish := start + length - 1.
   palindrome := (input at: start) = (input at: finish)
    and: [length <= 2 or: [(table at: start + 1) at: finish - 1]].
   (table at: start) at: finish put: palindrome.
   (palindrome and: [length > bestLength]) ifTrue: [
    bestStart := start. bestLength := length]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
{solve value: ''. solve value: 'x'.
 solve value: 'BABAD'. solve value: 'ABBA'. solve value: 'abc'}

Expected: #(#(0 0 '') #(1 1 'x') #(1 3 'BAB') #(1 4 'ABBA') #(1 1 'a'))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Test empty input and deliberate ties
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Try AAAA. Overlapping candidates are allowed, and the complete four-character input wins.

Download this checkpoint

06 - Compare against an independent exhaustive oracle

A slow oracle copies and reverses every substring. Its loops are ordered differently from the dynamic program, but it uses the same earliest-start tie rule. Exhaustively check all 127 strings of length zero through six over the alphabet a,b. This checks small cases, not a proof for every possible input.

Independent Workspace expression - select all, then Print it
| solve oracle checked text |
solve := [:input |
 | n table bestStart bestLength finish palindrome |
 n := input size. bestStart := 0. bestLength := 0.
 table := (1 to: n) collect: [:row | Array new: n withAll: false].
 1 to: n do: [:length |
  1 to: n - length + 1 do: [:start |
   finish := start + length - 1.
   palindrome := (input at: start) = (input at: finish)
    and: [length <= 2 or: [(table at: start + 1) at: finish - 1]].
   (table at: start) at: finish put: palindrome.
   (palindrome and: [length > bestLength]) ifTrue: [
    bestStart := start. bestLength := length]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
oracle := [:input |
 | n bestStart bestLength part |
 n := input size. bestStart := 0. bestLength := 0.
 1 to: n do: [:start |
  start to: n do: [:finish |
   part := input copyFrom: start to: finish.
   (part = part reversed and: [part size > bestLength]) ifTrue: [
    bestStart := start. bestLength := part size]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
checked := 0.
0 to: 6 do: [:n |
 0 to: (2 raisedTo: n) - 1 do: [:mask |
  text := String new: n.
  1 to: n do: [:i |
   text at: i put: ((mask bitAt: i) = 0 ifTrue: [$a] ifFalse: [$b])].
  (solve value: text) = (oracle value: text)
   ifFalse: [Error signal: 'Palindrome disagreement'].
  checked := checked + 1]].
checked

Expected: 127

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Compare against an independent exhaustive oracle
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Extend the bound to eight: the expected number of tested strings becomes 511. The oracle is intentionally slower and uses more copying.

Download this checkpoint

07 - Trade the table for expansion around centers

Every palindrome has either one middle character or a gap between two middle characters. Expand around both kinds of center until the ends differ or leave the input. This alternative still takes quadratic time in the worst case, but uses constant extra working space, excluding its returned substring. Explicit tie handling keeps the same answer as the table method.

Independent Workspace expression - select all, then Print it
| solve expand |
solve := [:input |
 | n table bestStart bestLength finish palindrome |
 n := input size. bestStart := 0. bestLength := 0.
 table := (1 to: n) collect: [:row | Array new: n withAll: false].
 1 to: n do: [:length |
  1 to: n - length + 1 do: [:start |
   finish := start + length - 1.
   palindrome := (input at: start) = (input at: finish)
    and: [length <= 2 or: [(table at: start + 1) at: finish - 1]].
   (table at: start) at: finish put: palindrome.
   (palindrome and: [length > bestLength]) ifTrue: [
    bestStart := start. bestLength := length]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
expand := [:input |
 | n bestStart bestLength left right length |
 n := input size. bestStart := 0. bestLength := 0.
 1 to: n do: [:pivot |
  0 to: 1 do: [:gap |
   left := pivot. right := pivot + gap.
   [left >= 1 and: [right <= n and: [(input at: left) = (input at: right)]]]
    whileTrue: [
     length := right - left + 1.
     (length > bestLength or: [length = bestLength and: [left < bestStart]])
      ifTrue: [bestStart := left. bestLength := length].
     left := left - 1. right := right + 1]]].
 {bestStart. bestLength. bestLength = 0
  ifTrue: [''] ifFalse: [input copyFrom: bestStart to: bestStart + bestLength - 1]}].
#('' 'a' 'abba' 'BANANA' 'BABAD' 'aaaa' 'abc')
 allSatisfy: [:sample | (solve value: sample) = (expand value: sample)]

Expected: true

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Trade the table for expansion around centers
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Why are both center kinds needed? Removing gap=1 loses even-length palindromes such as ABBA.

Download this checkpoint

08 - Count work and state the invariant

For n characters there are n(n+1)/2 nonempty intervals. The table algorithm tests each once and stores n squared booleans, so both time and allocated table space are quadratic. At the start of a length pass, every shorter interval is correct; matching endpoints plus the correct interior proves the next interval. This is not the linear-time Manacher algorithm.

Independent Workspace expression - select all, then Print it
| n visits |
n := 20. visits := 0.
1 to: n do: [:length |
 1 to: n - length + 1 do: [:start | visits := visits + 1]].
{visits. n * (n + 1) // 2. n squared.
 (n * 2) * ((n * 2) + 1) // 2}

Expected: #(210 210 400 820)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Count work and state the invariant
Genuine native Squeak Workspace capture. The validation harness evaluated this code and displayed its actual result below it.

Try it: Count only interval visits, not the oracle or screenshot work. Doubling n almost quadruples visits; the exact ratio approaches four.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Palindrome tables: find the longest mirrored substring 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

A substring is contiguous. Deleting letters to form a palindromic subsequence solves a different problem; do not substitute the longest-common-subsequence recurrence.

Use one fresh Array per row. Smalltalk and:/or: blocks short-circuit; eager Boolean operators would evaluate invalid interior indexes on short intervals.

The earliest-start tie rule is part of the contract. Different traversal orders can choose another equally long answer unless ties are handled explicitly.

This quadratic table is suited to teaching and modest inputs. Very long text needs a more space-efficient or asymptotically faster algorithm. Character-level equality does not automatically model human-visible graphemes.

Three practice challenges

Ignore case deliberately

Find a palindrome in Racecar without changing the solver.

Show solution

Pass 'Racecar' asLowercase to solve. It returns racecar. Decide separately whether to return characters from the original string, since normalization can change position mappings in more general text.

Return all best starts

How would you keep every longest palindrome, rather than one?

Show solution

Maintain a collection of starts. On a strictly longer palindrome clear it and add the new start. On an equal best length append the start. Avoid storing copied substrings inside the table loop.

Explain a false interval

Why is ABCA not palindromic even though its endpoints match?

Show solution

Its interior BC is not a palindrome. Equal endpoints are necessary but insufficient for length greater than two.

Continue learning

Longest Common Subsequence | Edit Distance | First Slice

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