Sub topic 5
Computing the Prefix Function in Linear Time
This chapter assumes you know what a border is and what pi[i] means: the length of the longest proper border of p[0..i]. It also assumes you can read Python loops and Big-O notation. The goal is to compute the whole pi array in O(m) time for a pattern of length m.
Why the obvious method is too slow
You could compute pi[i] by testing every candidate length from i down to 1. For each length you would check whether that prefix equals the suffix of the same length. That costs O(m) per position and O(m²) or worse overall. The linear algorithm avoids it by reusing values it has already computed.
Two facts that make reuse possible
Fact 1: the value grows by at most one per step. Suppose p[0..i] has a border of length k. Drop its last character and you get a border of length k - 1 of p[0..i-1]. So pi[i] <= pi[i-1] + 1.
Fact 2: the borders form a chain. A border of a border is also a border. So the borders of p[0..i-1], from longest to shortest, have these lengths:
pi[i-1]pi[pi[i-1] - 1]pi[pi[pi[i-1] - 1] - 1], and so on down to 0.
Each border of p[0..i] is some border of p[0..i-1] extended by p[i]. To find pi[i], walk down the chain and stop at the first length k where p[k] == p[i]. The answer is then k + 1. If no length works, pi[i] is 0, unless p[0] == p[i], in which case it is 1.
The algorithm
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]At the start of each iteration, k holds pi[i-1], the longest border you could extend. The while loop moves down the border chain until it finds a border that p[i] extends, or until k reaches 0.
A trace with a fallback
Here is the trace for p = "aabaaab":
| i | p[i] | k before | comparisons | pi[i] |
|---|---|---|---|---|
| 1 | a | 0 | p[0]=a matches | 1 |
| 2 | b | 1 | p[1]=a fails, k=pi[0]=0; p[0]=a fails | 0 |
| 3 | a | 0 | p[0]=a matches | 1 |
| 4 | a | 1 | p[1]=a matches | 2 |
| 5 | a | 2 | p[2]=b fails, k=pi[1]=1; p[1]=a matches | 2 |
| 6 | b | 2 | p[2]=b matches | 3 |
At i = 5 the border "aa" cannot be extended to "aab". The algorithm drops to the next border in the chain, "a", and extends that to "aa". It never compares a character twice in a way that rebuilds work from scratch.
Why it is linear
The while loop sits inside a for loop, so the code looks quadratic. It is not. k goes up by at most 1 per iteration, so its total increase is at most m − 1. Every pass of the while loop lowers k by at least 1, and k never goes below 0. The total number of while passes, over the whole run, is therefore at most m − 1. A later chapter turns this into a formal amortized proof.
Exercise
Compute the prefix function of "ababaca" by hand, showing each fallback.
Show answer
[0, 0, 1, 2, 3, 0, 1]. At i = 5 ('c'), k = 3: p[3]='b' fails, so k = pi[2] = 1. Then p[1]='b' fails, so k = pi[0] = 0. Then p[0]='a' fails, so pi[5] = 0. At i = 6, 'a' matches p[0], so pi[6] = 1.
Exercise
For a pattern of length m, what is the largest possible total number of while-loop iterations across the whole run, and why?
Show answer
At most m − 1. Each iteration adds at most 1 to k, so k's total increase is at most m − 1. Each while pass lowers k by at least 1, and k never goes negative, so the total number of passes cannot exceed the total increase.