The Z Algorithm
In short: the Z-array answers the mirror question to KMP's — z[i] is how
far the string starting at i copies the string's own beginning. A Z-box
[l, r) remembers the furthest-right match found so far; inside it, a new
value starts at min(r − i, z[i − l]) from its mirror position and only
extends past what's already known, which keeps the whole scan at O(n).
Gluing pattern + separator + text and reading where z equals the
pattern's length turns the same algorithm into a search.
![A Z-box 4, 7) on "aabaaab"; z[5] is copied from its mirror z[1] = 1 with no character comparison
KMP answers "how much of the pattern is matched ending here?" The Z algorithm answers the mirror-image question: "how much of the string's beginning is repeated starting here?" Both run in linear time. Z is often the easier of the two to get right under pressure, because its invariant is something you can draw: a box.
The Z-array
For a string s, z[i] is the length of the longest common prefix of s and
s[i:], meaning how many characters starting at i copy the start of the string.
By convention here z[0] = len(s), since the whole string trivially copies itself.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| s | a | a | b | a | a | a | b |
| z | 7 | 1 | 0 | 2 | 3 | 1 | 0 |
z[4] = 3 because s[4:] is aab, which starts the same way as s for three
characters. z[2] = 0 because b doesn't match a at all.
In Quarry this is the prefix profiler. For every position in a block of text,
it says how far the text there echoes a given beginning. Pattern search comes
straight out of it: glue the pattern, a separator and the text together, and every
position where z equals the pattern's length is a match.
The direct way compares from scratch at every position:
s = "aaaa"
z = [len(s)]
for i in range(1, len(s)):
k = 0
while i + k < len(s) and s[k] == s[i + k]:
k += 1
z.append(k)
print(z)