Sub topic 6
Searching the Text with KMP
This chapter assumes you can read Python, know zero-based indexing, and have the prefix_function from the previous chapter. Recall that pi[i] is the length of the longest proper border of p[0..i]. Here that table drives a search that reads each text character once and never moves backward in the text.
The state you carry
KMP keeps one integer, k, while it scans the text left to right. After it processes text position i, k is the length of the longest prefix of the pattern that ends exactly at i. In other words, pattern[0:k] == text[i-k+1 : i+1], and no longer prefix of the pattern ends there.
This single number replaces all the restarts the naive search does. To process the next character c, there are only two questions:
- Does
cextend the current partial match? This is true whenc == pattern[k]. - If not, what is the next shorter prefix that still ends at the previous position and might be extended by
c?
The prefix function answers the second question. The prefixes of the pattern that end at the current position are exactly the borders of pattern[0:k]. The next shorter one has length pi[k - 1]. So on a mismatch, KMP falls back k = pi[k - 1] and tries again. It stops when c matches or k reaches 0.
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
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]The search loop has the same shape as prefix_function. That is intentional. Computing pi is KMP searching the pattern against itself.
When k == m, the whole pattern ends at i, so the match starts at i - m + 1. The pattern cannot be extended past full length, so k falls back to pi[m - 1], the longest border of the full pattern. This keeps any overlap that could start the next match.
A worked trace
Pattern abab has pi = [0, 0, 1, 2]. Here is the text abababca:
| i | c | fallbacks | k after | event |
|---|---|---|---|---|
| 0 | a | none | 1 | |
| 1 | b | none | 2 | |
| 2 | a | none | 3 | |
| 3 | b | none | 4 | match at 0, k = pi[3] = 2 |
| 4 | a | none | 3 | |
| 5 | b | none | 4 | match at 2, k = 2 |
| 6 | c | 2 → pi[1] = 0 | 0 | |
| 7 | a | none | 1 |
At i = 6, the character c cannot extend ab. Its border is empty, and pattern[0] = 'a' doesn't match c either, so k drops to 0. The text index never decreased. Only k moved.
Common mistakes
- Using
pi[k]instead ofpi[k - 1].kis a length, and the border table is indexed by the last position. A prefix of lengthkends at indexk - 1. - Using
ifinstead ofwhilefor the fallback. One fallback may not be enough. You have to keep shrinking untilcfits orkis 0. - Resetting
k = 0after a match. This misses overlapping occurrences. The search above would return only[0]. - Comparing before falling back. The
whileloop has to run before thec == pattern[k]test. Otherwisekcan grow from a prefix that doesn't actually end at the previous position.
Exercise
The pattern "aab" has pi = [0, 1, 0]. Trace kmp_search("aaab", "aab"). Give the value of k after each text character and the list of matches returned.
Show answer
At i=0 ('a'), k becomes 1. At i=1 ('a'), pattern[1]='a' matches, so k becomes 2. At i=2 ('a'), pattern[2]='b' mismatches, so k falls back to pi[1]=1. Then pattern[1]='a' matches, so k becomes 2. At i=3 ('b'), pattern[2]='b' matches, so k becomes 3, which equals m. That records a match at 3-3+1=1, and k is reset to pi[2]=0. The k values are 1, 2, 2, 3 (then reset to 0), and the result is [1].
Exercise
Why does the search reset k to pi[m - 1] after a match instead of 0, and what would kmp_search("aaaa", "aa") return under each choice?
Show answer
pi[m - 1] is the longest border of the full pattern. Keeping it preserves the part of the current match that can begin the next occurrence. With k = pi[1] = 1, the result is [0, 1, 2]. With k = 0, the result is [0, 2], because overlapping matches are missed.