Sub topic 4
The Prefix Function
This chapter assumes you know what a border is from the previous chapter. A border of a string is a substring that is both a proper prefix and a suffix of it. It also assumes you can read Python and use zero-based indexing. Here we turn borders into a single array that KMP depends on.
Definition
For a pattern p of length m, the prefix function is an array pi of length m. Each entry is defined as follows:
pi[i]is the length of the longest proper border of the prefixp[0..i], which is the firsti + 1characters.- "Proper" means the border cannot be the whole prefix, so
pi[i] <= i. pi[0]is always 0, because a one-character string has no non-empty proper border.
You will see the same array under other names. Many textbooks call it the failure function, and many interview resources call it the LPS array ("longest proper prefix which is also a suffix"). All three names mean the same values.
Computing It by Hand
Take p = "abacaba". For each prefix, find the longest proper prefix that is also a suffix:
| i | p[0..i] | Longest proper border | pi[i] |
|---|---|---|---|
| 0 | a | (none) | 0 |
| 1 | ab | (none) | 0 |
| 2 | aba | a | 1 |
| 3 | abac | (none) | 0 |
| 4 | abaca | a | 1 |
| 5 | abacab | ab | 2 |
| 6 | abacaba | aba | 3 |
So pi = [0, 0, 1, 0, 1, 2, 3].
Look at how the values change from one entry to the next. An entry can go up by at most 1 (from i = 4 to 6), and it can drop sharply (from 1 to 0 at i = 3). The next chapter's linear-time algorithm relies on both facts.
A Direct Implementation from the Definition
The code below checks every candidate border length for every prefix. It runs in O(m³) time, so it is too slow for real use. It is still worth having as a reference you can trust when you test a faster version.
def prefix_function_naive(p):
pi = []
for i in range(len(p)):
s = p[:i + 1]
best = 0
for k in range(1, i + 1): # proper borders only: k <= i
if s[:k] == s[-k:]:
best = k
pi.append(best)
return pi
print(prefix_function_naive("abacaba")) # [0, 0, 1, 0, 1, 2, 3]
print(prefix_function_naive("aabaaab")) # [0, 1, 0, 1, 2, 2, 3]The Border Chain
pi[i] gives only the longest border, but the array also encodes every other border. A border of a border is itself a border of the original string. So if the longest border of p[0..i] has length k = pi[i], the next shorter border has length pi[k - 1], the one after that pi[pi[k - 1] - 1], and so on down to 0.
def all_borders(p, pi):
"""Lengths of all proper borders of p, longest first."""
result = []
k = pi[-1] if p else 0
while k > 0:
result.append(k)
k = pi[k - 1]
return result
p = "abacaba"
print(all_borders(p, prefix_function_naive(p))) # [3, 1]Why This Helps Matching
Suppose you have matched the first k characters of the pattern against the text, and the next character mismatches. The text you just read ends with p[0..k-1]. Any match that could still succeed must start with a prefix of the pattern that is also a suffix of p[0..k-1], which is a border. The longest such candidate has length pi[k - 1]. You can keep that many characters matched without reading any text again. Chapter 6 builds the full search on this idea.
Common Mistakes
- Counting the whole string as a border. If you do, every
pi[i]comes out asi + 1, which is wrong. Borders must be proper. - Off-by-one when following the chain. After a border of length
k, the next one ispi[k - 1], notpi[k]. The entry for a prefix of lengthkis stored at indexk - 1. - Assuming the borders cannot overlap. In
"aaaa", the border"aaa"overlaps itself. This is allowed, and it givespi = [0, 1, 2, 3].
Exercise
Compute the prefix function of "ababab" by hand, then use the border chain to list every proper border length of the whole string.
Show answer
pi = [0, 0, 1, 2, 3, 4]. The chain starts at pi[5] = 4 ("abab"), then pi[3] = 2 ("ab"), then pi[1] = 0, so the border lengths are 4 and 2.
Exercise
Why can pi[i + 1] never be larger than pi[i] + 1?
Show answer
If p[0..i+1] has a border of length L, removing the last character from both copies of that border gives a border of p[0..i] of length L - 1. So pi[i] >= pi[i + 1] - 1.