s LearnSqueak.com

STRING ALGORITHMS · PREFIX FALLBACK

KMP substring search: reuse a partial match

Build a prefix table and an exact substring matcher in Squeak. Find overlapping occurrences without restarting the text scan, then check the result against a simple oracle.

8 runnable checkpoints143 native assertionsOverlapping matches

Before you start

Use native Squeak 6.1 and a Workspace. Read blocks and closures and collections first. Each numbered block is independent: copy the entire expression, including its temporary-variable declaration, select all of it, and choose Print it. Later checkpoints repeat the local definitions intentionally, so they also work in a fresh Workspace. No classes or packages are installed.

This is exact, contiguous substring matching. It does not calculate edit distance, tokenize documents or look up words in a prefix trie. It returns an Array of all 1-based start positions, including overlaps. It compares Characters exactly and rejects an empty pattern. The examples are small ASCII strings; no claim about grapheme-cluster indexing or Unicode normalization is made.

Download the eight Workspace checkpoints, the standalone assertion test, or the complete source kit. Open the checkpoint file as text and run one complete expression at a time, not the whole collection as a file-in.

01 · Count matched characters, not array positions

Squeak strings start at index 1. Our matched counter is a length: zero means nothing matched yet, so the next character is at matched + 1. A border is a proper prefix that is also a suffix. In ABABA, ABA is a border of length three; the whole word is not a proper prefix.

Independent Workspace expression · select all, then Print it
| pattern |
pattern := 'ABABA'.
{pattern first. pattern size.
 (pattern copyFrom: 1 to: 3) =
 (pattern copyFrom: 3 to: 5)}

Expected: {$A. 5. true}. The result is the character A, the length 5, and true. The border overlaps itself, which is allowed.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 1: Count matched characters, not array positions, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

02 · Compute the longest-border table

For every prefix ending at i, store its longest border length. On a mismatch, use the already computed table to try a shorter border. The and: block is lazy: it prevents access at index zero. The first table entry stays zero because a one-character string has no nonempty proper border.

Independent Workspace expression · select all, then Print it
| prefix |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
prefix value: 'ABABACA'

Expected: #(0 0 1 2 3 0 1). At position five, ABABA retains three matched characters. At position six, ABABAC has no nonempty border.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 2: Compute the longest-border table, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

03 · Follow more than one fallback

A mismatch may need several shorter candidates, not just one if statement. Suppose five characters of ABABACA matched but the next text character is X. The fallback chain is five, three, one, zero. The same text character is reconsidered at each candidate; the text index does not move backwards.

Independent Workspace expression · select all, then Print it
| table matched trace |
table := #(0 0 1 2 3 0 1).
matched := 5. trace := OrderedCollection with: matched.
[matched > 0] whileTrue: [
 matched := table at: matched. trace add: matched].
trace asArray

Expected: #(5 3 1 0). This is a border-chain demonstration, not the full search. Replacing whileTrue: with ifTrue: would skip necessary fallback candidates.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 3: Follow more than one fallback, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

Watch the border chain shrink

NATIVE SQUEAK CAPTURE
Native Squeak border-chain window showing lengths five, three, one and zero; five is highlighted
Four genuine Morphic captures replay computed fallback states. This is a captured-state animation, not mouse footage.

Download the visual expression, select it all in Workspace and Do it. Set stage to 0, 1, 2 or 3 to inspect a state. Close the previous window before opening another. The fixed 1000 × 400 drawing uses no timer, external package, network request or persistence. Its four values are computed by following the table, not pasted into the image.

04 · Find every exact occurrence

Combine preprocessing with one forward pass over the text. After consuming character i, matched is the length of a pattern prefix matching the text suffix. A full match begins at i minus pattern size plus one. Save that index and fall back immediately so the next comparison never tries pattern size + 1.

Independent Workspace expression · select all, then Print it
| prefix search |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
search := [:text :pattern |
 | table matched found |
 pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
 table := prefix value: pattern. matched := 0.
 found := OrderedCollection new.
 1 to: text size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (text at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (text at: i)
   ifTrue: [matched := matched + 1].
  matched = pattern size ifTrue: [
   found add: i - pattern size + 1.
   matched := table at: matched]].
 found asArray].
search value: 'ABABABACA' value: 'ABACA'

Expected: #(5). The array contains starting position 5. Select the entire block, including both local block definitions, each time.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 4: Find every exact occurrence, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

05 · Keep overlapping matches

Do not reset matched to zero after a hit. A suffix of the completed match may already begin the next match. The prefix table keeps exactly that information. Searching AAA in AAAAA must report three starts, even though the occurrences share characters.

Independent Workspace expression · select all, then Print it
| prefix search |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
search := [:text :pattern |
 | table matched found |
 pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
 table := prefix value: pattern. matched := 0.
 found := OrderedCollection new.
 1 to: text size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (text at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (text at: i)
   ifTrue: [matched := matched + 1].
  matched = pattern size ifTrue: [
   found add: i - pattern size + 1.
   matched := table at: matched]].
 found asArray].
search value: 'AAAAA' value: 'AAA'

Expected: #(1 2 3). Changing the post-match fallback to zero loses the overlapping starts 2 and 3.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 5: Keep overlapping matches, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

06 · Make boundary contracts explicit

This lesson deliberately rejects an empty pattern instead of deciding whether it matches every gap. An empty text and a pattern longer than the text both return an empty array. Catch the deliberate Error only in this test; ordinary callers should supply a nonempty pattern.

Independent Workspace expression · select all, then Print it
| prefix search |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
search := [:text :pattern |
 | table matched found |
 pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
 table := prefix value: pattern. matched := 0.
 found := OrderedCollection new.
 1 to: text size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (text at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (text at: i)
   ifTrue: [matched := matched + 1].
  matched = pattern size ifTrue: [
   found add: i - pattern size + 1.
   matched := table at: matched]].
 found asArray].
{search value: '' value: 'A'.
 search value: 'AB' value: 'ABCD'.
 [search value: 'ABC' value: ''. false]
  on: Error do: [:error | true]}

Expected: {#(). #(). true}. The result contains two empty arrays and true for the rejected empty pattern. This contract differs from some library search APIs.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 6: Make boundary contracts explicit, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

07 · Separate matching from case policy

The matcher compares Characters exactly. A and a are different. If your application wants ASCII case-insensitive matching, normalize both inputs before searching; do not silently change the algorithm. General Unicode normalization and user-visible character positions require a more careful contract than this ASCII example.

Independent Workspace expression · select all, then Print it
| prefix search |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
search := [:text :pattern |
 | table matched found |
 pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
 table := prefix value: pattern. matched := 0.
 found := OrderedCollection new.
 1 to: text size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (text at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (text at: i)
   ifTrue: [matched := matched + 1].
  matched = pattern size ifTrue: [
   found add: i - pattern size + 1.
   matched := table at: matched]].
 found asArray].
{search value: 'AbAaba' value: 'aba'.
 search value: 'AbAaba' asLowercase value: 'aba'}

Expected: {#(4). #(1 4)}. Exact matching finds only position 4; the explicitly lowercased ASCII input also finds position 1.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 7: Separate matching from case policy, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

08 · Check a second pattern and reuse preprocessing deliberately

This repeated DNA-like text contains two exact ATA starts. The current search block computes its table on every call. For many texts sharing one pattern, extract preprocessing into a compiled-pattern object that owns the pattern and table together, rather than caching a table without its matching pattern.

Independent Workspace expression · select all, then Print it
| prefix search |
prefix := [:pattern |
 | table matched |
 table := Array new: pattern size withAll: 0. matched := 0.
 2 to: pattern size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (pattern at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (pattern at: i)
   ifTrue: [matched := matched + 1].
  table at: i put: matched].
 table].
search := [:text :pattern |
 | table matched found |
 pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
 table := prefix value: pattern. matched := 0.
 found := OrderedCollection new.
 1 to: text size do: [:i |
  [matched > 0 and: [(pattern at: matched + 1) ~= (text at: i)]]
   whileTrue: [matched := table at: matched].
  (pattern at: matched + 1) = (text at: i)
   ifTrue: [matched := matched + 1].
  matched = pattern size ifTrue: [
   found add: i - pattern size + 1.
   matched := table at: matched]].
 found asArray].
search value: 'ATATGATA' value: 'ATA'

Expected: #(1 6). The answer is 1 and 6, not 1 and 3. Matching is contiguous, not a subsequence search.

NATIVE SQUEAK CAPTURE
Native Squeak Workspace checkpoint 8: Check a second pattern and reuse preprocessing deliberately, with its evaluated result selected
Actual Squeak 6.1 Workspace after Print it; the selected text is the computed result.

Why falling back is safe

Imagine the already matched part of the text under the same-length prefix of the pattern. If the next character disagrees, any viable shorter match must be both a suffix of that text and a prefix of the pattern. A border is precisely this overlap. The longest one is tried first; if it fails, its own border is tried. Lengths strictly decrease, so fallback terminates at zero.

The important separation is between the text position i and the count matched. The outer loop advances i exactly once per text character. The inner loop may compare that character with several pattern positions, but it only moves matched backwards. A successful comparison increases matched by one. After recording a full match, the proper-border fallback preserves possible overlaps and restores a valid next pattern index.

There are two similar loops, but their roles differ: preprocessing reads the pattern to build its table; searching reads the text using that table. Mixing text indices into preprocessing, or using a zero-based formula in Squeak’s 1-based Array, is an easy way to produce plausible-looking wrong results.

Compare against a deliberately simpler oracle

The downloadable test repeats every published checkpoint, then compares the matcher with a straightforward candidate-by-candidate substring check over 12 texts and 11 nonempty patterns. The matrix includes empty text, one-character inputs, repeated characters, longer-than-text patterns, whole-text matches, missing symbols and overlapping results. Three additional prefix-table checks cover the empty table, repeated A and distinct characters. That is 143 assertions in native Squeak, not a claimed SUnit suite.

Open kmp-tests.st as text, select the entire expression and Print it. Expect 143. A false condition signals Error. The oracle is intentionally slower and simpler: it copies a candidate substring and compares it with the pattern. Sharing the prefix table with the oracle would make the two implementations vulnerable to the same mistake.

Tests support these explicit contracts; they do not prove arbitrary text encodings, every runtime or every future edit. Add a failing case before changing behavior. For a reusable application, migrate the checks into SUnit and give the compiled-pattern object its own tests.

Linear scanning is not a universal speed claim

For pattern length m and text length n, the prefix-table version uses O(m) preprocessing storage and O(n + m) comparisons overall, plus storage for the returned match positions. The inner while loop does not imply quadratic work: every decrease of matched spends progress gained by earlier increases. The same amortized argument applies while building the table.

These are algorithmic bounds under ordinary indexed access and constant-cost Character comparison, not measured timings. Our implementation allocates a table for each call and an OrderedCollection for results. Small inputs can favor an existing library primitive; use representative measurements before replacing production code. The oracle deliberately allocates substrings, but the KMP scan does not. This article does not claim a benchmark against Squeak’s built-in string search.

Make a small extension, then retain the tests

  1. Add a first-match interface. Decide whether no match returns zero, nil or another value, document it and test it separately from this all-matches contract.
  2. Make a compiled-pattern object that owns a copied pattern and prefix table. Search multiple texts without recomputing preprocessing; do not allow a changed pattern to reuse a stale table.
  3. Generate every A/B text up to a small length and compare against the oracle. Include patterns longer than the text, and keep the empty-pattern rejection test.
  4. For streaming chunks, carry the matched count and total offset between chunks. Test a pattern split across a chunk boundary before claiming streaming support.

Sources and related lessons

Cornell CS312 Lecture 26: String search explains the partial-match invariant and prefix fallback underlying KMP. It uses a first-match interface and different index notation; this lesson’s original Smalltalk implementation explicitly returns all 1-based starts and preserves overlaps. Source reviewed 27 October 2026. The code, assertion matrix and native demonstrations here were written and executed for this lesson.

Continue with collections, SUnit and document indexing. Use the SqueakJS playground for its existing prepared demos; this exact KMP lesson is native-only, not an advertised embedded demo.