Sub topic 8
Why KMP Never Misses a Match
KMP skips shifts. After a mismatch it never re-reads text it has already seen, and it never checks most of the alignments that naive search checks. That raises a fair question: how do we know none of the skipped alignments was a match? This chapter answers it with a precise invariant and a short proof.
This chapter assumes you have read the earlier chapters on borders, the prefix function pi, and the kmp_search loop. You should be comfortable with proof by induction and with the notation p[:j], which means the first j characters of p.
Alignments and prefixes are the same thing
An alignment, or shift, s places the pattern's first character under text[s]. Naive search tests every alignment separately. KMP looks at the same information differently.
Suppose we have read the text up to index i. Call alignment s alive at i if every pattern character placed so far agrees with the text, that is, text[s..i] == p[0..i-s]. An alive alignment is exactly a prefix of the pattern, p[:j] with j = i - s + 1, that ends at text position i.
So "which alignments are still possible?" becomes "which prefixes of the pattern are suffixes of text[:i+1]?" An alignment that is not alive at i can never become a match, because it already has a mismatch. Discarding it loses nothing.
KMP keeps a single number k, the length of the longest such prefix. Equivalently, k identifies the leftmost alive alignment. The rest of the proof shows two things. First, k always has this meaning. Second, every other alive alignment can be recovered from k through the prefix function.
The invariant
Let m = len(p) with m >= 1. Here is the search loop from the earlier chapter:
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]Invariant. At the end of each iteration i, after any reset:
kis the length of the longest prefix ofpwith length less thanmthat is a suffix oftext[:i+1].i - m + 1was appended tomatchesif and only ifpitself is a suffix oftext[:i+1].
Part 2 is the statement we actually want: a match is reported at position i exactly when one ends there. Part 1 is the information we carry forward to make part 2 provable. The phrase "less than m" matters. After a full match the loop resets k, so k never stays equal to m between iterations.
Before iteration 0 we have read nothing, and the only prefix ending "there" is the empty one, so k = 0 is correct as the base case.
Two lemmas
Lemma 1: the border chain lists every border
Recall that pi[j-1] is the length of the longest proper border of p[:j].
If u is a border of v and w is a border of u, then w is also a border of v. The reason is that w is a prefix of u, which is a prefix of v. Likewise w is a suffix of u, which is a suffix of v.
The converse also holds. Let b be the longest proper border of v, and let w be any shorter border of v. Then w and b are both prefixes of v, so w is a prefix of b. They are also both suffixes of v, so w is a suffix of b. Therefore w is a border of b.
Put these together. The sequence
k, pi[k-1], pi[pi[k-1]-1], ..., 0
lists every border of p[:k], in strictly decreasing length, with none skipped. Each step moves to the longest border of the current one, and by the converse argument nothing lies between two consecutive steps.
Lemma 2: a new prefix comes from an old one
Suppose p[:j+1] is a suffix of text[:i+1]. Remove the last character from both. Then p[:j] is a suffix of text[:i].
By the invariant at step i-1, the longest such prefix with length below m has length k_old. We have j + 1 <= m, so j < m, which gives j <= k_old. Now p[:j] and p[:k_old] are both suffixes of text[:i], and the shorter one is a suffix of the longer. p[:j] is also a prefix of p[:k_old]. So p[:j] is a border of p[:k_old], or equal to it.
Combining the lemmas, every prefix that can end at position i has the form p[:j] + c with j somewhere in the border chain of k_old and p[j] == c.
The inductive step
Assume the invariant holds after iteration i-1, and let c = text[i].
The while loop walks the border chain of k_old from longest to shortest. It stops at the first j where p[j] == c, or at j = 0. By Lemma 1 the walk visits every candidate, in decreasing order. By Lemma 2 those candidates are the only possibilities. So the first j that extends gives the longest prefix ending at i, and the if that follows sets k = j + 1. If no candidate extends, including the empty prefix (because p[0] != c), then k stays 0, which is also correct.
Now there are two cases.
- If
k < m, no full match ends ati, nothing is appended, andkalready satisfies part 1. - If
k == m, the whole pattern ends ati, so appendingi - m + 1is correct. Part 1 needs the longest prefix with length belowmending ati. That prefix is a suffix oftext[:i+1]and also, because it is shorter thanp, a suffix ofp, so it is the longest proper border ofp. Its length ispi[m-1], which is exactly the value of the reset.
Both parts hold after iteration i, so by induction they hold for the whole text. KMP reports every occurrence and only real occurrences.
A worked trace
Pattern abab has pi = [0, 0, 1, 2]. Text is abababca.
| i | c | border chain tried | k after step | match? | longest prefix below m ending at i |
|---|---|---|---|---|---|
| 0 | a | 0 | 1 | no | a |
| 1 | b | 1 | 2 | no | ab |
| 2 | a | 2 | 3 | no | aba |
| 3 | b | 3 | 4, reset to 2 | at 0 | ab |
| 4 | a | 2 | 3 | no | aba |
| 5 | b | 3 | 4, reset to 2 | at 2 | ab |
| 6 | c | 2, 0 | 0 | no | (empty) |
| 7 | a | 0 | 1 | no | a |
The last two columns always agree. At i = 6 the chain goes 2 → pi[1] = 0, and neither p[2] = 'a' nor p[0] = 'a' equals c. So no alignment survives, and KMP has missed nothing.
Checking the invariant mechanically
A proof tells you why the algorithm works. A test that asserts the invariant shows that your particular code matches the proof. The version below computes the "true" k by brute force after each step and compares.
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_ending_at(text, pattern, i, limit):
for j in range(min(limit, i + 1), -1, -1):
if text[i - j + 1:i + 1] == 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
matched = False
if k == m:
matches.append(i - m + 1)
matched = True
k = pi[k - 1]
# Part 1: k is the longest prefix shorter than m ending at i.
assert k == longest_prefix_ending_at(text, pattern, i, m - 1), (text, pattern, i)
# Part 2: a match is reported exactly when one ends here.
assert matched == (i >= m - 1 and text[i - m + 1:i + 1] == pattern)
return matches
random.seed(1)
for _ in range(20000):
pattern = "".join(random.choice("ab") for _ in range(random.randint(1, 6)))
text = "".join(random.choice("ab") for _ in range(random.randint(0, 15)))
kmp_checked(text, pattern)
print("invariant held on all tests")A small alphabet such as "ab" matters here. Small alphabets produce many repeated borders, which is where buggy fallback code breaks.
How common bugs break the invariant
Each classic KMP bug corresponds to a specific step of the proof that it violates.
| Bug | Proof step violated | Symptom |
|---|---|---|
| `k = 0` after a match | Reset must be the longest proper border, `pi[m-1]` | Overlapping matches missed: `"aaaa"`, `"aa"` gives `[0, 2]` instead of `[0, 1, 2]` |
| `if` instead of `while` for fallback | Lemma 1 requires walking the whole chain | `k` stops at a border that does not extend |
| `pi[k]` instead of `pi[k-1]` | Chain must use borders of `p[:k]` | Wrong candidates, sometimes an index error |
| Comparing with `p[k]` after `k == m` without reset | `k < m` between iterations | `IndexError` on `pattern[m]` |
Here is the if bug made concrete. Take pattern abacabax, with pi = [0, 0, 1, 0, 1, 2, 3, 0], and text abacababacabax. After reading abacaba, k = 7. The next character is b. The correct loop tries 7, then 3, then 1, finds p[1] = 'b', and sets k = 2. A single if falls back once to 3, sees p[3] = 'c', and leaves k = 3. That claims aba ends at a position where the text reads bab. The error spreads, and the buggy version returns [], while the true answer is [6].
The same proof covers the prefix function
prefix_function is KMP run on the pattern against itself, starting at index 1 so that no prefix matches itself trivially. The invariant reads: after step i, k is the longest proper border of p[:i+1]. Lemmas 1 and 2 apply unchanged. The pi values it reads, pi[k-1] with k - 1 < i, have already been computed, so the induction is well founded.
Exercise
Suppose you change the reset after a match to k = 0. Using the invariant, explain which part fails and give the shortest text where the output changes for pattern "aa".
Show answer
Part 1 fails. After a match the longest prefix shorter than m ending at i is pi[m-1] = 1 (the string "a"), but k is set to 0. The alive alignment starting at i is discarded even though it has no mismatch. Text "aaa" shows the difference: the correct output is [0, 1], and the buggy version returns [0].
Exercise
In Lemma 2 we used j + 1 <= m to conclude j <= k_old. Why does this step need part 1 of the invariant to talk about prefixes shorter than m, rather than all prefixes?
Show answer
Lemma 2 needs kold to bound every j with p[:j] ending at i-1 and j < m. That is exactly the "longest prefix with length below m" from part 1. If kold were allowed to equal m, the loop would read pattern[m], which does not exist. Prefixes of length m never need to be extended, since no prefix of length m + 1 exists.
Exercise
Pattern "abab", text "abababca". At i = 6 (character 'c') the chain tried is 2 then 0. List every alignment that was alive at i = 5 and explain why none survives at i = 6.
Show answer
At i = 5 the prefixes ending there with length below 4 are "ab" (k = 2, alignment s = 4) and the empty prefix (alignment s = 6). The longest one, length 4, was the reported match at s = 2. At i = 6, extending "ab" needs p[2] = 'a', and extending the empty prefix needs p[0] = 'a'. The character is 'c', so both fail and k = 0. No alignment starting at or before 6 is alive, so nothing was skipped wrongly.