The Knuth-Morris-Pratt Algorithm
The automaton matcher reads every text character once but needs a table with a row for every character of the alphabet. Knuth, Morris and Pratt (1977, with Morris's version from 1970) found that a single array of numbers, the prefix function, contains all the information that matters. When a mismatch happens after matched characters, the prefix function says how many of them can be kept. The result is a matcher with worst-case time and extra space, whose analysis is a classic of amortized reasoning.
What a mismatch tells us
Suppose characters of the pattern have matched, so the text ends with , and the next text character differs from . The naive algorithm would shift by one and start over. But we know the last text characters: they are . The next possible match must start inside this stretch at a position where a prefix of is also a suffix of . The longest such prefix gives the smallest safe shift.
The prefix function of is
("Proper" means shorter than itself.) For $P = $ ababcab:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| a | b | a | b | c | a | b | |
| 0 | 0 | 1 | 2 | 0 | 1 | 2 |
So after matching abab and failing, the algorithm continues as if ab ( characters) had matched, without moving backwards in the text.
The algorithm
PREFIX-FUNCTION(P) KMP-MATCH(T, P)
1 pi[0] = 0; k = 0 1 pi = PREFIX-FUNCTION(P); q = 0
2 for q = 1 to m - 1 2 for i = 0 to n - 1
3 while k > 0 and P[k] != P[q] 3 while q > 0 and P[q] != T[i]
4 k = pi[k - 1] 4 q = pi[q - 1] // fall back
5 if P[k] == P[q] 5 if P[q] == T[i]
6 k = k + 1 6 q = q + 1
7 pi[q] = k 7 if q == m
8 return pi 8 report i - m + 1
9 q = pi[m - 1]The two procedures are the same loop: computing is matching the pattern against itself. In both, the variable ( or ) is the number of characters currently matched, and the inner while follows the chain of ever shorter prefixes that are also suffixes, until one can be extended or none is left.
The animation computes the prefix function of ababcab and then matches it against a text with two overlapping-looking occurrences.
The program prints the same steps as the animation.
def prefix_function(P):
pi, k = [0] * len(P), 0
for q in range(1, len(P)):
while k > 0 and P[k] != P[q]:
k = pi[k - 1]
if P[k] == P[q]:
k += 1
pi[q] = k
return pi
def kmp(T, P, verbose=False):
pi, q, found, comparisons = prefix_function(P), 0, [], 0
for i, c in enumerate(T):
while q > 0 and P[q] != c:
comparisons += 1
if verbose:
print(f" text {i}: {c} != {P[q]}, fall back q = pi[{q - 1}] = {pi[q - 1]}")
q = pi[q - 1]
comparisons += 1
if P[q] == c:
q += 1
if verbose:
print(f" text {i}: {c} matches pattern {q - 1}, q = {q}")
elif verbose:
print(f" text {i}: {c} != {P[0]}, move on")
if q == len(P):
found.append(i - len(P) + 1)
if verbose:
print(f" match at shift {i - len(P) + 1}, continue with q = pi[{len(P) - 1}] = {pi[-1]}")
q = pi[q - 1]
return found, comparisons
P = "ababcab"
print("pi =", prefix_function(P))
found, comps = kmp("abababcabababcabc", P, verbose=True)
print("matches at", found, "with", comps, "character comparisons for 17 text characters")pi = [0, 0, 1, 2, 0, 1, 2]
text 0: a matches pattern 0, q = 1
text 1: b matches pattern 1, q = 2
text 2: a matches pattern 2, q = 3
text 3: b matches pattern 3, q = 4
text 4: a != c, fall back q = pi[3] = 2
text 4: a matches pattern 2, q = 3
text 5: b matches pattern 3, q = 4
text 6: c matches pattern 4, q = 5
text 7: a matches pattern 5, q = 6
text 8: b matches pattern 6, q = 7
match at shift 2, continue with q = pi[6] = 2
text 9: a matches pattern 2, q = 3
text 10: b matches pattern 3, q = 4
text 11: a != c, fall back q = pi[3] = 2
text 11: a matches pattern 2, q = 3
text 12: b matches pattern 3, q = 4
text 13: c matches pattern 4, q = 5
text 14: a matches pattern 5, q = 6
text 15: b matches pattern 6, q = 7
match at shift 9, continue with q = pi[6] = 2
text 16: c != a, fall back q = pi[1] = 0
text 16: c != a, move on
matches at [2, 9] with 20 character comparisons for 17 text characters
Linear time by amortization
The inner while loop can run many times for one character, so a quick look suggests . The truth is for the matcher and for the prefix function, by the potential method (The Potential Method) with the potential .
- Every iteration of the inner
whileloop decreases , since . - Each step of the outer loop increases by at most 1 (line 6).
- never becomes negative.
So over the whole run, the total number of decreases is at most the total number of increases, which is at most . The inner loop runs at most times in total, and the matcher makes at most character comparisons (one successful or final comparison per character, plus one per fallback). The same argument with gives at most comparisons for the prefix function. Total: time, space.
Why the fallback chain finds every candidate
The prefixes of that are suffixes of , from longest to shortest, are , , and so on until length 0. Indeed, if is a proper prefix that is a suffix of with , then is also a suffix of the longer , hence a prefix-suffix of , and by induction it appears in the chain from there. So following the chain visits every possible partial match in decreasing order, and the first one that can be extended by the next character is the longest one: the matcher never skips a valid shift.
The program measures the comparisons on texts designed to be hard for the naive algorithm and on random text.
import random
def kmp_comparisons(T, P):
pi, k = [0] * len(P), 0
for q in range(1, len(P)):
while k > 0 and P[k] != P[q]:
k = pi[k - 1]
if P[k] == P[q]:
k += 1
pi[q] = k
q, comps, found = 0, 0, 0
for c in T:
while q > 0 and P[q] != c:
comps += 1
q = pi[q - 1]
comps += 1
if P[q] == c:
q += 1
if q == len(P):
found += 1
q = pi[q - 1]
return comps, found
def naive_comparisons(T, P):
c = 0
for s in range(len(T) - len(P) + 1):
for j in range(len(P)):
c += 1
if T[s + j] != P[j]:
break
return c
rng = random.Random(6)
cases = [("a" * 3000, "a" * 99 + "b"), ("ab" * 1500, "ab" * 50 + "b"),
("".join(rng.choice("ab") for _ in range(3000)), "abbabaabab")]
for T, P in cases:
kc, found = kmp_comparisons(T, P)
print(f"n = {len(T)}, m = {len(P):3}: KMP {kc:5} comparisons (<= 2n = {2 * len(T)}), "
f"naive {naive_comparisons(T, P):6}, matches {found}")n = 3000, m = 100: KMP 5901 comparisons (<= 2n = 6000), naive 290100, matches 0
n = 3000, m = 101: KMP 4450 comparisons (<= 2n = 6000), naive 147900, matches 0
n = 3000, m = 10: KMP 4471 comparisons (<= 2n = 6000), naive 5951, matches 3
On the repetitive texts the naive algorithm makes 30 to 50 times as many comparisons, and the factor grows with ; KMP never exceeds . On random text both are fast, and KMP gains little: its advantage is the guarantee.
In C++
KMP in C++, returning every occurrence, the function asked for in the practice problem.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
std::vector<int> prefix_function(const std::string& P) {
std::vector<int> pi(P.size(), 0);
for (size_t q = 1, k = 0; q < P.size(); q++) {
while (k > 0 && P[k] != P[q]) k = pi[k - 1];
if (P[k] == P[q]) k++;
pi[q] = int(k);
}
return pi;
}
std::vector<int> find_all(const std::string& T, const std::string& P) {
std::vector<int> found;
if (P.empty() || P.size() > T.size()) return found;
auto pi = prefix_function(P);
size_t q = 0;
for (size_t i = 0; i < T.size(); i++) {
while (q > 0 && P[q] != T[i]) q = pi[q - 1];
if (P[q] == T[i]) q++;
if (q == P.size()) { found.push_back(int(i + 1 - P.size())); q = pi[q - 1]; }
}
return found;
}
int main() {
auto pi = prefix_function("ababcab");
std::printf("pi:");
for (int v : pi) std::printf(" %d", v);
std::printf("\n");
for (auto [T, P] : std::vector<std::pair<std::string, std::string>>{
{"abababcabababcabc", "ababcab"}, {"aaaaa", "aa"}, {"mississippi", "issi"}, {"abc", "d"}}) {
std::printf("find_all(\"%s\", \"%s\") =", T.c_str(), P.c_str());
for (int s : find_all(T, P)) std::printf(" %d", s);
std::printf("\n");
}
}pi: 0 0 1 2 0 1 2
find_all("abababcabababcabc", "ababcab") = 2 9
find_all("aaaaa", "aa") = 0 1 2 3
find_all("mississippi", "issi") = 1 4
find_all("abc", "d") =
Overlapping occurrences are all reported (aa occurs four times in aaaaa, issi twice in mississippi). Practise with Find Every Occurrence (KMP). The prefix function has many other uses: the length of the shortest period of a string is , and running it on P#T (with a separator not in either string) finds the matches as positions where the value reaches .
Test yourself
What is the prefix function of aabaaab?
- 0 1 0 1 2 2 3
- 0 1 0 1 2 3 4
- 0 0 1 0 1 2 3
- 0 1 2 0 1 2 3
Why does KMP make at most character comparisons while matching?
- Because the pattern is preprocessed
- Each fallback decreases , which grows by at most 1 per text character, so there are at most fallbacks in total
- Because
- Because it skips half of the text
After reporting a match, what value does KMP give to ?
- 0
What is the space needed by KMP besides the text and the pattern?