SMALLTALK LAB
Z search: reuse prefix matches to find every occurrence
Compute a Z array, reuse a known prefix-matching interval, and locate overlapping text matches with an explicit separator and native Squeak visual checkpoints.
Before you begin
Use native Squeak 6.1 and Workspace Print it. Strings and Arrays are one-based. Z[i] is the number of characters matching the beginning of a String when comparison starts at position i. We deliberately set Z[1]=0 rather than the full length. The examples use case-sensitive character equality and ASCII text.
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 - Measure a prefix match directly
Starting at position 3 in ababa, compare the suffix aba with the start of the String. Three characters match. This naive comparison makes the Z definition concrete before optimizing it.
| text start length |
text := 'ababa'. start := 3. length := 0.
[(start + length <= text size) and:
[(text at: length + 1) = (text at: start + length)]]
whileTrue: [length := length + 1].
lengthExpected: 3

Try it: Position 2 begins with b, so its match length is zero. Position 5 has only one character left and therefore cannot match more than one.
02 - Build a slow reference array
Repeat the direct comparison independently at each position. The first entry stays zero by convention. This simple implementation may compare the same characters many times, but it is ideal as a small-input reference.
| text z |
text := 'ababa'. z := Array new: text size withAll: 0.
2 to: text size do: [:i | | length |
length := 0.
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length].
zExpected: #(0 0 3 0 1)

Try it: For aaaaa the slow result is #(0 4 3 2 1). Its repeated rescanning shows why a reusable interval is useful.
03 - Understand the matching interval
A known interval left..right matches the String prefix of the same length. If i lies inside it, its offset maps to prefix position i-left+1. Reuse that earlier Z value only up to the current right boundary; anything beyond right remains unverified.
| left right i earlier |
left := 3. right := 5. i := 5. earlier := #(0 0 3 0 0).
{i - left + 1. right - i + 1.
((right - i + 1) min: (earlier at: i - left + 1))}Expected: #(3 1 1)

Try it: The mirrored Z value is 3, but only one character is guaranteed inside the interval. Capping it is essential.
04 - Extend only beyond what is known
The optimized block begins with the safe reused length, then compares forward while characters still match. When a match extends farther right, record its interval. Positions already inside an interval can often be resolved with no new successful comparisons.
| zValues |
zValues := [:text | | z left right |
z := Array new: text size withAll: 0. left := 0. right := 0.
2 to: text size do: [:i | | length |
length := 0.
i <= right ifTrue: [length := (right - i + 1) min: (z at: i - left + 1)].
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length.
i + length - 1 > right ifTrue: [left := i. right := i + length - 1]].
z].
zValues value: 'aabcaabxaaaz'Expected: #(0 1 0 0 3 1 0 0 2 2 1 0)

Try it: At position 5 the prefix aab matches, then x differs from c. Check that the interval is inclusive and its end is i+length-1.
05 - Handle repeated and empty text
A repeated String produces long prefix matches at many positions. The reusable interval avoids restarting from zero each time. Empty and one-character Strings have no positions after the first to process.
| zValues |
zValues := [:text | | z left right |
z := Array new: text size withAll: 0. left := 0. right := 0.
2 to: text size do: [:i | | length |
length := 0.
i <= right ifTrue: [length := (right - i + 1) min: (z at: i - left + 1)].
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length.
i + length - 1 > right ifTrue: [left := i. right := i + length - 1]].
z].
{zValues value: 'aaaaa'. zValues value: ''. zValues value: 'x'}Expected: #(#(0 4 3 2 1) #() #(0))

Try it: The convention Z[1]=0 is deliberate. Do not mix it with another implementation that puts the String size in the first entry.
06 - Turn prefix matches into substring matches
Join pattern, a separator absent from both inputs, and text. A Z value at least the pattern length in the text portion means the whole pattern matched. Subtract pattern size and the one separator to recover a one-based text index.
| zValues find |
zValues := [:text | | z left right |
z := Array new: text size withAll: 0. left := 0. right := 0.
2 to: text size do: [:i | | length |
length := 0.
i <= right ifTrue: [length := (right - i + 1) min: (z at: i - left + 1)].
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length.
i + length - 1 > right ifTrue: [left := i. right := i + length - 1]].
z].
find := [:pattern :text | | joined z matches |
pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
((pattern includes: $#) or: [text includes: $#])
ifTrue: [Error signal: 'Choose inputs without the separator'].
joined := pattern, '#', text. z := zValues value: joined.
matches := OrderedCollection new.
(pattern size + 2) to: joined size do: [:i |
(z at: i) >= pattern size ifTrue: [matches add: i - pattern size - 1]].
matches asArray].
{find value: 'aba' value: 'ababa'.
find value: 'aa' value: 'aaaa'}Expected: #(#(1 3) #(1 2 3))

Try it: Matches overlap: after finding aa at 1, the search still reports 2 and 3. No greedy skip removes them.
07 - Make boundary policies explicit
The matcher rejects empty patterns rather than choosing a convention for every insertion position. It also rejects the reserved separator in either input. No matches, a pattern longer than the text, and empty text all yield an empty Array.
| zValues find |
zValues := [:text | | z left right |
z := Array new: text size withAll: 0. left := 0. right := 0.
2 to: text size do: [:i | | length |
length := 0.
i <= right ifTrue: [length := (right - i + 1) min: (z at: i - left + 1)].
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length.
i + length - 1 > right ifTrue: [left := i. right := i + length - 1]].
z].
find := [:pattern :text | | joined z matches |
pattern isEmpty ifTrue: [Error signal: 'Use a nonempty pattern'].
((pattern includes: $#) or: [text includes: $#])
ifTrue: [Error signal: 'Choose inputs without the separator'].
joined := pattern, '#', text. z := zValues value: joined.
matches := OrderedCollection new.
(pattern size + 2) to: joined size do: [:i |
(z at: i) >= pattern size ifTrue: [matches add: i - pattern size - 1]].
matches asArray].
{find value: 'cat' value: 'dog'.
find value: 'long' value: 'lo'. find value: 'a' value: ''.
([find value: '' value: 'abc'. false] on: Error do: [:error |
error messageText = 'Use a nonempty pattern']).
([find value: 'a#' value: 'abc'. false] on: Error do: [:error |
error messageText = 'Choose inputs without the separator'])}Expected: #(#() #() #() true true)

Try it: A separator that appears in the inputs breaks the stated construction contract. For general data, use a sequence with an out-of-band sentinel rather than guessing a rare character.
08 - Compare the optimized array with direct scans
The naive oracle recomputes every prefix match independently. Compare it with the optimized result on repeated characters, mixed strings, empty input and a longer pattern. This tests Z computation without using substring-search indexing as a second source of uncertainty.
| zValues naive fixtures |
zValues := [:text | | z left right |
z := Array new: text size withAll: 0. left := 0. right := 0.
2 to: text size do: [:i | | length |
length := 0.
i <= right ifTrue: [length := (right - i + 1) min: (z at: i - left + 1)].
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length.
i + length - 1 > right ifTrue: [left := i. right := i + length - 1]].
z].
naive := [:text | | z |
z := Array new: text size withAll: 0.
2 to: text size do: [:i | | length |
length := 0.
[(i + length <= text size) and:
[(text at: length + 1) = (text at: i + length)]]
whileTrue: [length := length + 1].
z at: i put: length]. z].
fixtures := #('' 'a' 'aaaaa' 'ababa' 'aabcaabxaaaz' 'abcababcab').
fixtures collect: [:text | (zValues value: text) = (naive value: text)]Expected: #(true true true true true true)

Try it: Extend fixtures with random short strings from a small alphabet. Repeated prefixes and mismatches just beyond the saved interval are especially valuable tests.
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
Every index in this lesson is one-based. The matching interval is inclusive, so its length is right-left+1 and the mirrored prefix position is i-left+1. Porting zero-based formulas without translating both offsets causes subtle errors.
Z[1]=0 is a representation convention, not a claim that the String fails to match itself. The algorithm never needs a full self-match at that entry. Empty input returns an empty Array.
The rightmost matching boundary never moves backward. New successful comparisons that extend it account for at most a linear number of character advances; each outer iteration has at most one failing comparison. The optimized Z calculation is O(n) time and O(n) additional array storage under constant-time indexed character access.
The search constructs pattern + separator + text, costing O(m+n) storage and time. It reports all overlapping matches. This implementation requires a nonempty pattern and excludes # from both inputs; these explicit restrictions avoid ambiguous boundary behavior.
Equality is character-by-character and case-sensitive. These examples do not implement case folding, Unicode normalization or user-perceived grapheme matching. A String index is not necessarily a display-column position.
Three practice challenges
Translate a match index
For a pattern of length 3, a combined-string match begins at position 8. Which text position is it?
Show solution
It is 8-3-1=4. The first three positions hold the pattern, and position 4 holds the separator, so text starts at combined position 5.
Predict repeated matches
What does searching aaa in aaaaa return?
Show solution
It returns #(1 2 3). Each is a full three-character match, and overlaps are allowed.
Test interval capping
Why not copy the entire mirrored Z value when i is inside the interval?
Show solution
Only characters through the current right boundary are known to match. A mirrored value can extend beyond that guarantee. Start with min(mirrored value, right-i+1), then compare beyond the boundary explicitly.
Continue learning
Kmp Search | Prefix Trie | Document Search
Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.