Sub topic 8
Why KMP Never Misses a Match
This chapter assumes you already know the prefix function pi, the meaning of a border, and the KMP search loop from the previous chapters. The question here is a reasonable worry. When KMP hits a mismatch, it jumps k straight to pi[k - 1] and never looks at the text again. Could that jump skip over a real occurrence? The answer is no, and the reason comes down to one invariant.
The Invariant
Let T be the text and P the pattern, with m = len(P). KMP keeps a single number k while it scans. The claim is:
After KMP processes T[i], and before any reset that follows a match, k equals the length of the longest prefix of P that is also a suffix of T[0..i].
If this holds at every position, matches cannot be missed. An occurrence of P ending at i means the full pattern, of length m, is a suffix of T[0..i]. Since no prefix is longer than m, the longest such prefix must have length m, so k == m at that step and KMP reports it.
Why the Fallback Chain Is Complete
Suppose the invariant holds after T[i - 1] with value k, and the next character is c = T[i]. Any prefix of length j that ends at i consists of a prefix of length j - 1 ending at i - 1, followed by c. Two facts follow:
j - 1 <= k, becausekwas the longest prefix ending ati - 1.P[0..j-2]is a suffix ofP[0..k-1](both end at the same text position) and also a prefix of it. So it is a border ofP[0..k-1], or the whole of it.
The candidates for j - 1 are therefore k and the lengths of the borders of P[0..k-1]. The chain k, pi[k-1], pi[pi[k-1]-1], ..., 0 lists exactly those lengths, longest first, because the longest border of a border is the next shorter border. The while loop walks this chain and stops at the first length whose next character equals c. Since it tries candidates in decreasing order, the first success is the longest one. No valid length sits between two links of the chain, so the jump skips nothing.
The Reset After a Match
After reporting a match, KMP sets k = pi[m - 1]. A prefix of length m can't be extended, but the next step only needs prefixes ending at i of length below m. The longest of those is the longest proper border of P, which is pi[m - 1]. The invariant still holds for every length that matters, and this reset is why overlapping occurrences are found.
Checking the Invariant in Code
A proof is easier to trust after you've watched it hold. The version below asserts the invariant at every step against a brute-force computation. It also compares the results with naive search on random inputs.
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 longest_prefix_suffix(text, pattern, end):
for j in range(min(len(pattern), end), -1, -1):
if text[end - j:end] == pattern[:j]:
return j
def kmp_checked(text, pattern):
m = len(pattern)
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
assert k == longest_prefix_suffix(text, pattern, i + 1)
if k == m:
matches.append(i - m + 1)
k = pi[k - 1]
return matches
def naive_search(text, pattern):
m = len(pattern)
return [i for i in range(len(text) - m + 1) if text[i:i + m] == pattern]
random.seed(1)
for _ in range(2000):
t = "".join(random.choice("ab") for _ in range(random.randint(0, 30)))
p = "".join(random.choice("ab") for _ in range(random.randint(1, 5)))
assert kmp_checked(t, p) == naive_search(t, p)
print("invariant held on all tests")Common Errors
| Mistake | Effect on the invariant |
|---|---|
| Using `if` instead of `while` for fallback | Only one border is tried, so shorter valid prefixes are missed |
| Resetting `k = 0` after a match | Overlapping matches are lost |
| Falling back with `pi[k]` instead of `pi[k - 1]` | Jumps to the wrong border and can index past the pattern |
Exercise
Pattern "aab", text "aaab". After reading T[0..1] = "aa", k = 2. At T[2] = 'a' a mismatch occurs with P[2] = 'b'. Which values does k take next, and why does KMP still find the match at index 1?
Show answer
pi = [0, 1, 0], so k falls back to pi[1] = 1. P[1] = 'a' matches, so k becomes 2: "aa" is the longest prefix ending at index 2. At T[3] = 'b', P[2] = 'b' matches, so k = 3 = m and KMP reports a match at 3 - 3 + 1 = 1. The fallback kept the border "a", which is the start of the real occurrence.
Exercise
Why does replacing the while loop with a single if break correctness? Give a pattern that shows it.
Show answer
A single step tries only pi[k - 1]. If that border also fails to extend, the shorter borders further down the chain are never tried, so k becomes 0 even though a shorter prefix could match. Take P = "abacabab" and T = "abacabab". After "abacaba", k = 7 and P[7] = 'b' matches, so try a mismatching case instead: T = "abacabaab". At T[7] = 'a', P[7] = 'b' fails. Fallback to pi[6] = 3 compares P[3] = 'c' and fails. A single if stops there, but the correct chain continues to pi[2] = 1, where P[1] = 'b' fails, then to 0, where P[0] = 'a' matches, giving k = 1. With a single if, k ends up 0 and the occurrence chances starting at index 7 are lost.