Sub topic 2
Computing the Prefix Function in Linear Time
This chapter assumes you know Python loops and zero-based indexing. It also assumes the definition of a border from the previous chapter. pi[i] is the length of the longest proper border of p[0..i].
Building pi from Its Own Earlier Values
Let k = pi[i - 1]. Every border of p[0..i] is a border of p[0..i-1] extended by one character. So the algorithm tries the longest candidate first: if p[i] == p[k], then pi[i] = k + 1. If the characters differ, the next shorter border of p[0..i-1] has length pi[k - 1]. The algorithm falls back to that border and tries again, and stops when it reaches k = 0.
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]The loop runs in O(m) time even though it contains a nested while. Each step of the for loop increases k by at most 1, and each fallback decreases it. So the total number of fallbacks over the whole run is at most m.
Searching the Text with KMP
The search uses the same loop, but over the text. k is the length of the longest pattern prefix that ends at the current text position. When k reaches m, the pattern matches. The text index i never moves backward. Run this code in the same file as prefix_function.
def kmp_search(text, pattern):
m = len(pattern)
if m == 0:
return list(range(len(text) + 1))
pi = prefix_function(pattern)
matches = []
k = 0
for i, c in enumerate(text):
while k > 0 and c != pattern[k]:
k = pi[k - 1]
if c == pattern[k]:
k += 1
if k == m:
matches.append(i - m + 1)
k = pi[k - 1]
return matches
print(kmp_search("abababca", "abab")) # [0, 2]
print(kmp_search("aaaa", "aa")) # [0, 1, 2]Edge Cases and Overlapping Matches
- Overlapping matches: after a match, the code sets
k = pi[m - 1]instead of 0. This keeps the longest border of the pattern, so the occurrences at 0, 1, and 2 in"aaaa"are all found. - Empty pattern: an empty pattern matches at every index from 0 to n. Without the guard, the code would read
pattern[0]and fail with anIndexError. - Pattern longer than text:
kcan never reachm, so the function returns[]. No special case is needed.
Exercise
Compute the prefix function of "aabaaab" by hand.
Show answer
[0, 1, 0, 1, 2, 2, 3]. At i = 5, the candidate k = 2 fails because 'a' differs from 'b'. The algorithm falls back to pi[1] = 1, and 'a' then matches, so pi[5] = 2.
Exercise
What does kmp_search("aaaaa", "aaa") return, and what would it return if k were reset to 0 after each match?
Show answer
It returns [0, 1, 2]. With the reset to 0, it would return only [0].