The Prefix Function & Z-Function in Depth
Failure links, string periods and matching automata.
The prefix function packs everything a string knows about its own overlaps into one array. Read it right and it lists every period of every prefix, builds a matching automaton, and counts the occurrences of every prefix, all in linear time. Behind it sits a 1965 theorem about periodic functions that tells you when two periods force a third.
What you’ll learn
- Prove that periods and borders are dual ( is a period iff is a border length) and that the chain lists every border.
- Prove the periodicity lemma of Fine and Wilf, and use it to show that a power's shortest root has length .
- Prove linear bounds for computing and with potential functions, and convert to .
- Build the KMP automaton, count the occurrences of every prefix, and state the lower bounds and the constant-space, real-time and streaming variants of matching.
Borders and periods
(a) Duality. The condition for all valid says, position by position, that the prefix of length equals the suffix of length :
Borders nest. Let and be borders of with . Then is a prefix of shorter than the prefix , so a prefix of ; likewise is a suffix of . Hence:
(b) The chain is complete. The longest border of is . Every shorter border of is a border of , and conversely every border of is a border of . So the next border is the longest border of , of length , and induction finishes the proof:
The prefix function of is . What are all the periods of ?
- 3 only
- 3, 6, 7 and 8
- 3 and 8
- 5, 2 and 1
Show the answer
B. 3, 6, 7 and 8
The border chain is , then , then , then 0: the borders , and . The periods are , , , and the trivial period 8.
The periodicity lemma
Setup. Let be periods and . We show that is a period: for every . Two cases cover all .
Case . Step forward by , then back by (the second step uses period at index , valid because ):
Case . Then , so step back by , then forward by (valid because ):
Euclid. So is a period, and still holds. Repeat the subtraction, as in the subtractive form of Euclid's algorithm, until the two periods become equal; they end at the gcd:
A string of length 9 has periods 4 and 6. What follows?
- Nothing more: the lemma needs length at least
- It has period 1
- It has period 10
- It has period 2
Show the answer
D. It has period 2
The sharp form needs only , so is a period. At length 7 it can fail: has periods 4 and 6 but not 2.
Linear time, and π versus Z
Both arrays come from algorithms whose inner loops look quadratic. A potential function makes the amortized argument exact.
The prefix function. At step , let be the number of fallbacks; the step makes comparisons. Each fallback lowers the current border length by at least 1, and the step raises it by at most 1:
Sum. With , the amortized cost is at most 2. Summing over , with and :
The Z-function. Take , the right end of the box. A comparison beyond the box that succeeds raises by one when the box is updated, and never decreases; each adds at most one failed comparison:
The two arrays describe the same self-overlaps from opposite ends. says that the prefixes of lengths occur starting at , so they end at positions and are borders of the prefixes ending there. Conversely, is the largest that appears on the border chain at position , so determines as well.
def z_to_pi(z):
n = len(z)
pi = [0] * n
for i in range(1, n):
for j in range(z[i] - 1, -1, -1): # prefix of length j + 1 ends at i + j
if pi[i + j] > 0:
break # set by a smaller i: a longer border
pi[i + j] = j + 1
return piLinear time: every entry is set once, and each breaks at most once. A smaller start gives a longer border at the same end position, so the first value written is the right one, and every entry below a set one is already set.
Automata and counting
def kmp_automaton(p, alphabet):
pi, m = prefix_function(p), len(p)
delta = [dict() for _ in range(m + 1)]
for q in range(m + 1):
for c in alphabet:
if q < m and p[q] == c:
delta[q][c] = q + 1
elif q == 0:
delta[q][c] = 0
else:
delta[q][c] = delta[pi[q - 1]][c] # already computed: pi[q-1] < q
return deltatime and space. Since , each missing transition copies one computed earlier, with no fallback loop at all.
The automaton spends exactly one table lookup per text character: it runs in real time. Plain KMP has the same total cost, at most comparisons, but can spend several of them on a single character. Knuth showed that this delay is , bounded by about with the golden ratio, and Fibonacci strings come close: a Fibonacci pattern of length 377 can force 12 comparisons on one character. Galil (1981) made matching real-time without an alphabet-sized table.
The prefix function also counts. Each position is the end of an occurrence of the prefix of length , and of every shorter border on its chain. Count the values of , push the counts down the chains in decreasing order of length, and add each prefix's own occurrence at position 0:
def prefix_occurrences(s):
n, pi = len(s), prefix_function(s)
cnt = [0] * (n + 1)
for i in range(n):
cnt[pi[i]] += 1 # the longest border ending at i
for L in range(n, 0, -1):
cnt[pi[L - 1]] += cnt[L] # its shorter borders end there too
for L in range(n + 1):
cnt[L] += 1 # the prefix itself, at position 0
return cnt[1:] # occurrences of s[:1], s[:2], ..., s[:n]For this returns : occurs four times, and twice each. Running the same trie-based idea for many patterns at once gives Aho–Corasick, whose failure links are the prefix function of a whole dictionary.
Lower bounds and the frontier
Linear time is the floor; the frontier is in the other resources.
- Constant extra space. KMP stores , words. Galil and Seiferas (1983) matched in linear time with extra space, and the Two-Way algorithm of Crochemore and Perrin (1991) does it simply, by splitting the pattern at a critical factorization, where the local period equals the global one. Two-Way is what glibc's
strstruses for long needles and what CPython falls back to since 3.10. - Streaming. If the text arrives one character at a time and even the pattern cannot be stored, Porat and Porat (2009) matched with words, combining the periodicity of prefixes with fingerprints, and showed space is needed; Breslauer and Galil (2014) made it real-time. These algorithms are randomized, with one-sided errors.
Key takeaways
- Periods and borders are dual: is a period of exactly when has a border of length , and the chain lists every border, hence every period.
- Fine and Wilf: periods and with force period , and the bound is sharp. Consequently a string is a power exactly when is a proper divisor of .
- and are computed in linear time by potential arguments ( and ), and each determines the other; converts to in .
- The KMP automaton spends exactly one transition per text character after preprocessing, and prefix-function counts give the number of occurrences of every prefix in .
- Every matcher must read text characters in the worst case (Rivest); Two-Way matches in linear time with extra space, and fingerprints give streaming matching in words.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A string of length 12 has . What is ?
- A primitive string: it is not a power of a shorter string
- for a string of length 6
- for a string of length 8
- for a string of length 4
Show the answer
D. for a string of length 4
The shortest period is , which divides 12, so , as in . It cannot also have period 6: periods 4 and 6 in a string of length would force period 2 by Fine–Wilf, contradicting that 4 is the shortest period.
Which string shows that the bound in the Fine–Wilf lemma cannot be lowered for , ?
Show the answer
D.
has length , period 3 () and period 5 (its first and last characters agree), but not period 1. One character longer, the lemma would force period 1.
Plain KMP and the KMP automaton both match in total time. What does the automaton add?
- Exactly one transition per text character, so constant work per character in the worst case, paid for with an table
- Fewer total comparisons on every input
- The ability to match several patterns at once
- Independence from the alphabet size
Show the answer
A. Exactly one transition per text character, so constant work per character in the worst case, paid for with an table
KMP's fallback loop can spend up to about comparisons on a single character, although the total stays below . The automaton precomputes the result of every fallback chain for every character, so each text character costs one lookup: real time.
Boyer–Moore often skips most of the text. Can any algorithm guarantee examining fewer than text characters on every input?
- Yes, Boyer–Moore with Galil's rule does
- Yes, with a large enough alphabet
- No: Rivest proved that some inputs force at least examined characters
- Only with randomization
Show the answer
C. No: Rivest proved that some inputs force at least examined characters
An adversary can hide an occurrence in any unexamined window, so in the worst case every algorithm reads at least characters (Rivest, 1977). Sublinear behavior is an average-case or typical-input property.
Further reading
- D. E. Knuth, J. H. Morris & V. R. Pratt, "Fast pattern matching in strings," SIAM Journal on Computing 6(2) (1977), 323–350.
- N. J. Fine & H. S. Wilf, "Uniqueness theorems for periodic functions," Proceedings of the American Mathematical Society 16 (1965), 109–114.
- R. L. Rivest, "On the worst-case behavior of string-searching algorithms," SIAM Journal on Computing 6(4) (1977), 669–674.
- M. Crochemore & D. Perrin, "Two-way string-matching," Journal of the ACM (1991).
- D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997).