Sub topic 4
The Prefix Function
This chapter assumes you know the following:
- Basic Python: loops, slicing, and list comprehensions.
- Zero-based indexing of strings and arrays.
- Big-O notation.
- The previous chapter's definitions. A proper border of a string
sis a string that is both a proper prefix and a proper suffix ofs. "Proper" means it is shorter thans.
The previous chapter looked at the borders of a single string. KMP needs more than that. It needs the longest proper border of every prefix of the pattern, computed once before the search starts. The array that stores these lengths is the prefix function. This chapter defines it, shows how to compute it by hand, and covers the properties that later chapters depend on. The fast linear-time algorithm is the subject of the next chapter. Here we work straight from the definition.
Definition
For a pattern p of length m, the prefix function is an array pi of length m where:
pi[i] is the length of the longest proper border of p[0..i], the prefix ending at index i inclusive.
If that prefix has no proper border, pi[i] is 0. The single-character prefix p[0..0] has only the empty string as a proper border, so pi[0] is always 0.
The same array appears under several names:
| Name | Where you see it |
|---|---|
| Prefix function, `pi` | Competitive programming, many algorithm texts |
| Failure function | Automata-based presentations and Aho-Corasick |
| LPS array ("longest proper prefix which is also suffix") | Interview prep sites and tutorials |
| `next` array | Knuth's original paper and many Chinese textbooks, often shifted by one or using -1 |
Computing It by Hand
Take p = "abacaba". For each index, write out the prefix and look for the longest string that is both a proper prefix and a proper suffix of it.
| i | p[0..i] | Longest proper border | pi[i] |
|---|---|---|---|
| 0 | a | (empty) | 0 |
| 1 | ab | (empty) | 0 |
| 2 | aba | a | 1 |
| 3 | abac | (empty) | 0 |
| 4 | abaca | a | 1 |
| 5 | abacab | ab | 2 |
| 6 | abacaba | aba | 3 |
So pi = [0, 0, 1, 0, 1, 2, 3].
A good way to work by hand is to try border lengths from longest to shortest. At i = 6, the candidates have lengths 6, 5, 4, 3, and so on. Compare p[0..k-1] with the last k characters:
- k = 6:
abacabvsbacaba. No match. - k = 5:
abacavsacaba. No match. - k = 4:
abacvscaba. No match. - k = 3:
abavsaba. Match, sopi[6] = 3.
The values can also drop. Take p = "aabaaab":
| i | p[0..i] | Longest proper border | pi[i] |
|---|---|---|---|
| 0 | a | (empty) | 0 |
| 1 | aa | a | 1 |
| 2 | aab | (empty) | 0 |
| 3 | aaba | a | 1 |
| 4 | aabaa | aa | 2 |
| 5 | aabaaa | aa | 2 |
| 6 | aabaaab | aab | 3 |
At i = 5 the value stays at 2 instead of rising to 3. The candidate aab does not match the suffix aaa. At i = 6 it rises again because the new b extends the border aa into aab.
Two extreme cases help you check your intuition:
"aaaa"gives[0, 1, 2, 3]. Every prefix has a border one character shorter than itself."abcd"gives[0, 0, 0, 0]. No character repeats, so no prefix has a non-empty border.
A Direct Implementation
The definition turns straight into code. This version is slow, but it is easy to trust. That makes it useful for testing the fast version in the next chapter.
def prefix_function_naive(p):
"""pi[i] = length of the longest proper border of p[0..i]."""
m = len(p)
pi = [0] * m
for i in range(m):
# Proper border of p[0..i] has length at most i (not i + 1).
for k in range(i, 0, -1):
if p[:k] == p[i - k + 1:i + 1]:
pi[i] = k
break
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]
print(prefix_function_naive("aaaa")) # [0, 1, 2, 3]
print(prefix_function_naive("abcd")) # [0, 0, 0, 0]The inner loop starts at k = i, not k = i + 1. Starting at i + 1 would compare the whole prefix with itself. That comparison always succeeds, so every entry would become pi[i] = i + 1. This is the most common bug when people code the definition directly.
The cost is O(m³) in the worst case. There are m positions, up to i candidate lengths at each one, and each slice comparison costs O(k). That is fine for testing and useless for real patterns.
Properties That KMP Relies On
The linear-time algorithm and the search itself both depend on a few facts about pi. Each fact has a short proof.
Property 1: pi rises by at most one per step
For every i, pi[i + 1] <= pi[i] + 1.
Proof: suppose p[0..i+1] has a proper border of length k > 0. Remove the last character from both the prefix copy and the suffix copy. What remains is a proper border of p[0..i] with length k - 1. So k - 1 <= pi[i].
This means pi can climb only one step at a time, though it can drop by any amount. The amortized analysis in a later chapter is built on this asymmetry.
Property 2: a border of a border is a border
Let b be a border of s, and let c be a border of b. Then c is a prefix of b, which is a prefix of s. Also c is a suffix of b, which is a suffix of s. So c is a border of s.
Property 3: pi lists every border, not just the longest
Property 3 is the one that matters most. The prefix function stores only the longest border of each prefix, yet it gives you all of them. The borders of p[0..i], from longest to shortest, have lengths:
pi[i], then pi[pi[i] - 1], then pi[pi[pi[i] - 1] - 1], and so on until you reach 0.
Proof sketch: let k = pi[i], so the longest border is p[0..k-1]. Any shorter border c of p[0..i] is a prefix of p[0..i] and is shorter than p[0..k-1], so it is a prefix of p[0..k-1]. It is also a suffix of p[0..i], and p[0..k-1] is a suffix of p[0..i], so c is a suffix of p[0..k-1]. That makes c a border of p[0..k-1]. Property 2 gives the converse. The second-longest border of p[0..i] is therefore the longest border of p[0..k-1], which has length pi[k - 1]. Repeating the argument walks down the whole chain.
The next code block uses prefix_function_naive from the block above, so put both in the same file. It walks the chain and checks Properties 1 and 3 against brute force on random strings.
import random
def borders_via_pi(p, i):
"""All proper border lengths of p[0..i], longest first, using pi."""
pi = prefix_function_naive(p)
result = []
k = pi[i]
while k > 0:
result.append(k)
k = pi[k - 1]
return result
def borders_brute(p, i):
s = p[:i + 1]
return [k for k in range(len(s) - 1, 0, -1) if s[:k] == s[-k:]]
print(borders_via_pi("abacaba", 6)) # [3, 1]
for _ in range(2000):
p = "".join(random.choice("ab") for _ in range(random.randint(1, 12)))
pi = prefix_function_naive(p)
assert pi[0] == 0
for i in range(len(p) - 1):
assert pi[i + 1] <= pi[i] + 1 # Property 1
for i in range(len(p)):
assert borders_via_pi(p, i) == borders_brute(p, i) # Property 3
print("all properties hold")Use the alphabet "ab" for tests like this one. A small alphabet produces many repeats and long borders, which is where bugs show up. Random strings over 26 letters almost never have interesting borders.
Why the Search Needs This Array
Here is the connection to search, without the full algorithm. Suppose that during a search the first k characters of the pattern match the text, and then the next character fails. The text you just read ends with p[0..k-1]. Any earlier occurrence that could still succeed must start with a prefix of the pattern that is also a suffix of p[0..k-1]. In other words, it must start with a border of p[0..k-1].
The longest such border has length pi[k - 1]. So you can keep pi[k - 1] characters as already matched and keep going, without stepping back in the text. If the next character fails again, Property 3 says the next candidate is pi[pi[k - 1] - 1], and so on down the chain. That fallback line, k = pi[k - 1], appears in both the linear-time construction and the search loop in the following chapters.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Counting the whole prefix as a border | `pi[i] == i + 1` everywhere | Limit candidates to length `<= i` |
| Using `pi[k]` instead of `pi[k - 1]` when falling back | Index errors, or skipped matches | `pi` is indexed by end position. Length `k` ends at `k - 1` |
| Mixing a `next` table with -1 sentinels into `pi`-style code | Values off by one, infinite loops | Pick one convention and check it on `"aaaa"` |
| Assuming `pi` never decreases | Wrong hand calculations | `pi` can fall to any smaller value, including 0 |
| Testing only on random text with many different letters | Bugs go unnoticed | Test on small alphabets and periodic strings |
Exercise
Compute the prefix function of "abababca" by hand.
Show answer
[0, 0, 1, 2, 3, 4, 0, 1]. The prefixes "aba", "abab", "ababa", and "ababab" have longest borders "a", "ab", "aba", and "abab". At "abababc" no border survives because "c" appears nowhere else, so the value drops to 0. Then "abababca" has border "a".
Exercise
For p = "aabaaab", list every proper border of the whole string using only the pi array [0, 1, 0, 1, 2, 2, 3]. Do not compare substrings.
Show answer
Start at pi[6] = 3, which gives "aab". Next is pi[3 - 1] = pi[2] = 0, so the chain stops. The only non-empty proper border is "aab" (length 3).
Exercise
Can a valid prefix function contain the sequence pi[3] = 1, pi[4] = 3? Explain using a property from this chapter.
Show answer
No. Property 1 says pi[i + 1] <= pi[i] + 1, so pi[4] can be at most 2. A border of length 3 for p[0..4] would mean p[0..3] has a border of length 2, which contradicts pi[3] = 1.
Exercise
Change the inner loop of prefixfunctionnaive to range(i + 1, 0, -1). What does it return for "abc", and why?
Show answer
It returns [1, 2, 3]. When k = i + 1, the slice p[:k] equals p[0:i + 1] exactly, so the whole prefix always "matches" itself and the loop breaks at once. That is a border but not a proper border, so this violates the definition.