Sub topic 5
Computing the Prefix Function in Linear Time
The previous chapter defined the prefix function: for a pattern p, pi[i] is the length of the longest proper border of p[0..i]. This chapter shows how to fill the whole array in O(m) time, where m is the pattern length. The same loop structure reappears almost unchanged in the KMP search over the text, so if you understand this chapter well, the search will feel familiar.
This chapter assumes you can read Python and work with zero-based indexing, slicing, and while loops. It also assumes you know Big-O notation, and that you know what a border is: a string that is both a proper prefix and a suffix.
A Baseline Straight from the Definition
The most direct method tries every candidate border length for every prefix and checks each candidate by comparing slices.
def prefix_function_slow(p):
m = len(p)
pi = [0] * m
for i in range(m):
for length in range(i, 0, -1): # proper borders only: length <= i
if p[:length] == p[i - length + 1:i + 1]:
pi[i] = length
break
return pi
print(prefix_function_slow("aabaaab")) # [0, 1, 0, 1, 2, 2, 3]This version is correct, and it is useful later as a reference for testing. It is also slow. There are m prefixes, up to m candidate lengths for each, and each slice comparison costs up to m character checks, so the worst case is O(m³). For a pattern of 10,000 characters that is far too much work. The linear algorithm rests on two observations that remove almost all of it.
Observation 1: The Prefix Function Grows by at Most One
Suppose p[0..i+1] has a border of length L > 0. If you remove the last character from both copies of that border, you get a border of p[0..i] of length L - 1. So the longest border of p[0..i] has length at least L - 1, which gives:
pi[i + 1] <= pi[i] + 1
This bounds the search. When moving from position i to i + 1, no candidate longer than pi[i] + 1 needs checking. It also says how a border can grow: by extending an existing border of the previous prefix with exactly one matching character. If p[i + 1] == p[pi[i]], the character right after the current border equals the new character, and pi[i + 1] = pi[i] + 1.
Observation 2: Borders of Borders
The extension can fail. When p[i + 1] != p[pi[i]], the algorithm needs the next shorter border of p[0..i] and must try to extend that one instead. The question is how to find it without searching.
Let k = pi[i], so p[0..k-1] is the longest border of p[0..i]. Any shorter border b of p[0..i] is a prefix of p[0..i] and also a suffix of it. Because b is shorter than k, it is also a prefix and a suffix of p[0..k-1]. In other words, b is a border of the border. The longest border of p[0..k-1] has length pi[k - 1], a value we have already computed.
Applying this repeatedly gives the complete list of border lengths of p[0..i], from longest to shortest:
pi[i], thenpi[pi[i] - 1], thenpi[pi[pi[i] - 1] - 1], and so on, until the length reaches 0.
This sequence is the fallback chain. Each step is a single array lookup, and no character comparisons are needed to move along it.
The Algorithm
Putting the two observations together: for each new position i, start from the previous answer k = pi[i - 1]. Walk down the fallback chain until the character after the border matches p[i] or the chain runs out. Then extend by one if the characters match.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
print(prefix_function("abacaba")) # [0, 0, 1, 0, 1, 2, 3]
print(prefix_function("aabaaab")) # [0, 1, 0, 1, 2, 2, 3]Each part of the loop has a specific job:
pi[0]stays 0, because a single character has no non-empty proper border. That is why the loop starts ati = 1.- At the top of each iteration,
kequalspi[i - 1]. The variable carries the previous answer forward, so no separate lookup is needed. - The
whileloop walks the fallback chain. It stops whenp[i] == p[k], meaning the border of lengthkcan be extended, or whenk == 0, meaning only the empty border is left. - The
ifperforms the extension. Whenk == 0, it comparesp[i]withp[0], which checks whether the new border has length 1.
A Full Trace
Here is the trace for p = "aabaaab". The column "k before" holds the value carried in from the previous iteration.
| i | p[i] | k before | Fallback steps | Compare | pi[i] |
|---|---|---|---|---|---|
| 1 | a | 0 | none | p[1]=a vs p[0]=a, match | 1 |
| 2 | b | 1 | b≠p[1]=a, k=pi[0]=0 | b vs p[0]=a, no | 0 |
| 3 | a | 0 | none | a vs p[0]=a, match | 1 |
| 4 | a | 1 | none | a vs p[1]=a, match | 2 |
| 5 | a | 2 | a≠p[2]=b, k=pi[1]=1 | a vs p[1]=a, match | 2 |
| 6 | b | 2 | none | b vs p[2]=b, match | 3 |
Row 5 shows the fallback chain at work. The prefix "aabaa" has longest border "aa". Extending it would require p[2] == 'a', but p[2] is 'b'. The next shorter border is "a" (length pi[1] = 1). Extending that requires p[1] == 'a', which holds, so pi[5] = 2 and the border is "aa". The algorithm never re-compared the characters inside the border. It only checked the one character that follows each candidate.
Why the Loop Is Linear
Inner while loops often mean quadratic time, but this one does not. The full proof is in the chapter on running time. The short version is to track the value of k:
kstarts at 0 and never goes below 0.- Each iteration of the
forloop increaseskby at most 1, through the singlek += 1. - Each iteration of the
whileloop decreaseskby at least 1, becausepi[k - 1] <= k - 1.
Over the whole run, k rises by at most m - 1 in total. It cannot fall by more than it rose, so the while body runs at most m - 1 times across all iterations combined. Adding the m - 1 outer iterations gives O(m) total work and O(m) extra space for the array.
Common Errors
These are the mistakes that show up most often in real implementations:
- Starting the loop at
i = 0. Ati = 0withk = 0, the checkp[0] == p[0]succeeds and setspi[0] = 1. That counts the whole one-character string as its own border, which violates the "proper" requirement, and every later value inherits the error. - Writing
k = pi[k]instead ofk = pi[k - 1]. This reads the wrong array slot, often indexk, which can lie past the computed region, and gives wrong values or anIndexError. - Using
ifinstead ofwhilefor the fallback. One fallback step is not always enough. The exercise below gives a string where theifversion fails. - Resetting
k = 0inside theforloop. This throws away the carried-over border. The loop then only finds borders that build up from scratch, so values likepi[6] = 3in the trace are lost. - Comparing
p[i]withp[k - 1]. The character that extends a border of lengthksits at indexk, immediately after the border.
The best defense is to compare against the slow version on many random small inputs. A small alphabet produces lots of repeated characters and therefore lots of non-trivial borders:
import random
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def prefix_function_slow(p):
pi = [0] * len(p)
for i in range(len(p)):
for length in range(i, 0, -1):
if p[:length] == p[i - length + 1:i + 1]:
pi[i] = length
break
return pi
random.seed(1)
for _ in range(5000):
s = "".join(random.choice("ab") for _ in range(random.randint(0, 12)))
assert prefix_function(s) == prefix_function_slow(s), s
print("all tests passed")The test also covers the boundary inputs. The empty string returns [], because the loop body never runs, and a single character returns [0].
Exercise
Compute the prefix function of "abcabcd" by hand, then check it with prefix_function.
Show answer
[0, 0, 0, 1, 2, 3, 0]. The borders "a", "ab", "abc" grow one character at a time at i = 3, 4, 5. At i = 6, 'd' fails to extend "abc" (p[3] = 'a'), and the fallback chain pi[2] = 0 leaves only the empty border. 'd' also differs from p[0], so pi[6] = 0.
Exercise
Replace the while with if in prefix_function and run it on "aaaab". What does it return, and why is that wrong?
Show answer
The correct answer is [0, 1, 2, 3, 0]. The if version returns [0, 1, 2, 3, 2]. At i = 4, k = 3 and 'b' != p[3], so the single fallback sets k = pi[2] = 2. The code then compares 'b' with p[2] = 'a', finds no match, and stores 2 without falling back further. "aaaab" has no non-empty border because it is the only string ending in 'b', so k had to keep falling back to 0.
Exercise
For a pattern of length m, what is the largest possible total number of while-loop iterations across the whole computation, and what kind of string comes close to it?
Show answer
At most m - 1, because k increases by at most 1 per outer iteration (at most m - 1 in total) and each while iteration decreases it by at least 1. A string like "aaa...ab" gets close: k climbs to m - 2 and then the final 'b' drives it back down to 0 through m - 2 fallback steps.