Sub topic 6
Searching the Text with KMP
This chapter assumes you already know what a border is and how to compute the prefix function pi of a pattern in linear time. Here pi[i] is the length of the longest proper border of p[0..i]. The chapter also assumes you can read Python and follow a loop trace by hand. With pi in hand, the search itself takes only a few lines. Most bugs come from getting those few lines slightly wrong.
The Search State
KMP reads the text from left to right, one character at a time, and never moves backward. It carries a single integer between steps:
kis the length of the longest prefix of the pattern that is also a suffix of the text read so far.
When k reaches m (the pattern length), the last m characters of the text equal the pattern, so you have found a match.
You already used this idea when computing the prefix function. There, k tracked the longest prefix of the pattern ending at position i of the pattern itself. The search loop is the same loop with the text standing in for the second copy of the pattern. Most of the code carries over unchanged.
The Three Moves
For each text character c, the algorithm does three things in order.
- Fall back on mismatch. While
k > 0andcdoes not equalpattern[k], setk = pi[k - 1]. The current partial match of lengthkcannot be extended byc. The next longest candidate that is still a suffix of the text is the longest border ofpattern[0..k-1], and that has lengthpi[k - 1]. - Extend on match. If
c == pattern[k], incrementk. - Report and continue. If
k == m, record a match starting ati - m + 1, then setk = pi[m - 1]so the search can keep going and find overlapping matches.
The Implementation
The function below is self-contained. It includes the prefix function so you can run it as shown.
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]
print(kmp_search("aaaa", "aa")) # [0, 1, 2]
print(kmp_search("abacabd", "abacaba")) # []The empty-pattern guard comes first because pattern[k] with k = 0 would raise an IndexError on an empty pattern. The convention used here, that an empty pattern matches at every position including the end, is covered in the edge-cases chapter.
Trace 1: Overlapping Matches
Pattern abab has pi = [0, 0, 1, 2]. Search in the text abababca:
| i | c | Fallbacks | k after step 2 | Match? | k after step 3 |
|---|---|---|---|---|---|
| 0 | a | none | 1 | no | 1 |
| 1 | b | none | 2 | no | 2 |
| 2 | a | none | 3 | no | 3 |
| 3 | b | none | 4 | yes, at 0 | pi[3] = 2 |
| 4 | a | none | 3 | no | 3 |
| 5 | b | none | 4 | yes, at 2 | pi[3] = 2 |
| 6 | c | 2 → pi[1] = 0 | 0 | no | 0 |
| 7 | a | none | 1 | no | 1 |
Look at what happens at i = 3. After the first match, the algorithm does not start over. The suffix ab of the matched text is also a prefix of the pattern, so k drops to 2 and not to 0. Two characters later, the second, overlapping match is complete. The text pointer i never moved backward, and no character of the text was compared twice in a way that required rereading.
Trace 2: A Chain of Fallbacks
The first trace never needed more than one fallback per character. Fallback chains get longer when the pattern has nested borders. Pattern abacaba has pi = [0, 0, 1, 0, 1, 2, 3]. Search in abacabd:
| i | c | Fallbacks | k after step |
|---|---|---|---|
| 0–5 | abacab | none | 6 |
| 6 | d | 6 → pi[5] = 2, then 2 → pi[1] = 0 | 0 |
At i = 6, the algorithm has matched abacab and needs pattern[6] = 'a', but the text has d. The next candidate is the longest border of abacab, which is ab (length 2). That would need pattern[2] = 'a' next, which also fails. The border of ab is empty, so k becomes 0, and d does not match pattern[0] either. The algorithm skipped the shifts 1, 2, 3, and 5 without testing them, because the prefix function already showed they could not lead to a match.
Why the Text Never Moves Backward
The naive algorithm, after a mismatch, moves the window one position right and compares the pattern again from its start. That rereads up to m - 1 text characters. KMP keeps the information those rereads would have produced. The value k says exactly how much of the recent text agrees with the pattern, and pi says how much of that agreement still holds after shifting. Because of this, KMP can process input that arrives in pieces, such as a network stream, a file read in blocks, or a log being tailed.
The class below keeps k between calls, so a match that crosses a chunk boundary is still found.
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
class KMPMatcher:
def __init__(self, pattern):
if not pattern:
raise ValueError("pattern must be non-empty")
self.pattern = pattern
self.pi = prefix_function(pattern)
self.k = 0 # longest pattern prefix ending at the current position
self.pos = 0 # number of characters consumed so far
def feed(self, chunk):
found = []
p, pi, m = self.pattern, self.pi, len(self.pattern)
for c in chunk:
while self.k > 0 and c != p[self.k]:
self.k = pi[self.k - 1]
if c == p[self.k]:
self.k += 1
self.pos += 1
if self.k == m:
found.append(self.pos - m)
self.k = pi[m - 1]
return found
matcher = KMPMatcher("abab")
print(matcher.feed("aba")) # []
print(matcher.feed("babca")) # [0, 2]The first match starts in the first chunk and ends in the second. The matcher stores only k, pos, the pattern, and pi, which is O(m) memory no matter how long the stream gets. Here the start index is pos - m and not pos - m + 1, because pos is incremented before the check and so already counts the current character.
Common Errors
Each mistake in the table below produces code that looks reasonable and passes some tests.
| Mistake | Symptom | Fix |
|---|---|---|
| `k = pi[k]` instead of `k = pi[k - 1]` | Wrong fallbacks, `IndexError` when `k == m` | `pi` is indexed by the last position of the prefix, so a prefix of length `k` uses `pi[k - 1]` |
| `if` instead of `while` for the fallback | Misses matches that need a chain of fallbacks, as in Trace 2 | Keep falling back until the character matches or `k == 0` |
| `k = 0` after a match | Misses overlapping matches: `"aaaa"` with `"aa"` gives `[0, 2]` | Set `k = pi[m - 1]` |
| No reset after a match | `pattern[k]` with `k == m` raises `IndexError` on the next character | Reset in the same iteration that reports the match |
| Recording `i - m` | Every start index is off by one | The match ends at `i`, so it starts at `i - m + 1` |
| Fallback condition `k >= 0` | Infinite loop or `pi[-1]` read | The guard must be `k > 0` |
| Recomputing `pi` per call in a loop over many texts | Correct but wastes O(m) per text | Compute `pi` once per pattern and reuse it |
You can confirm the overlap bug directly:
def kmp_search_reset_to_zero(text, pattern):
# Deliberately buggy: resets k to 0 after a match.
m = len(pattern)
pi = [0] * m
k = 0
for i in range(1, m):
while k > 0 and pattern[i] != pattern[k]:
k = pi[k - 1]
if pattern[i] == pattern[k]:
k += 1
pi[i] = k
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 = 0
return matches
print(kmp_search_reset_to_zero("aaaa", "aa")) # [0, 2], should be [0, 1, 2]What Comes Next
The loop is now complete, but two questions are still open. Why is it safe to skip the shifts the fallback jumps over? And why does the inner while not make the algorithm quadratic? Later chapters answer both: one proves the matching invariant, and another gives the amortized O(n + m) bound. The edge-cases chapter covers empty patterns, patterns longer than the text, and overlap in more detail.
Exercise
The pattern "aabaaa" has pi = [0, 1, 0, 1, 2, 2]. Run kmp_search on the text "aabaabaaa" by hand. List the value of k after processing each character and give the list of match positions.
Show answer
The values of k after each character are: i=0 'a' → 1; i=1 'a' → 2; i=2 'b' → 3; i=3 'a' → 4; i=4 'a' → 5; i=5 'b': mismatch with pattern[5]='a', fall back k = pi[4] = 2, then 'b' == pattern[2] so k → 3; i=6 'a' → 4; i=7 'a' → 5; i=8 'a' → 6 = m, so record a match at 8 - 6 + 1 = 3 and set k = pi[5] = 2. The match list is [3].
Exercise
A colleague replaces the fallback "while k > 0 and c != pattern[k]" with "if k > 0 and c != pattern[k]". Give a pattern and text for which the modified code misses a match, and explain why.
Show answer
Use pattern "abacaba" (pi = [0, 0, 1, 0, 1, 2, 3]) and text "abacabacaba". At i = 6, k = 6 and 'a' matches, giving a match at 0. Then k = pi[6] = 3, and the matcher keeps going until the second match at 4. That run works even with if. A case that breaks it is pattern "aab" (pi = [0, 1, 0]) with text "aaab". At i = 2, k = 2 and 'a' != pattern[2] = 'b'. A single fallback gives k = pi[1] = 1, then 'a' == pattern[1], so k = 2, and the match at 1 is found anyway. For a real failure, the fallback must need two steps before the character matches. Pattern "abacabab" with text "abacabab" works: pi = [0,0,1,0,1,2,3,2]. At i = 7, k = 7 and 'b' != pattern[7]? No, pattern[7] = 'b', so it matches. Simplest case: pattern "aaab" with text "aaaab". At i = 3, k = 3 and 'a' != 'b', and one fallback gives k = pi[2] = 2. Then 'a' == pattern[2], so k = 3 and the match at 1 is found. In general, a single 'if' fails when the first fallback still mismatches but a deeper border matches, as with pattern "abacabd" falling back from 6 to 2 to 0 and then needing pattern[0]. Concrete failure: pattern "abaabab" is not needed. Use pattern "ab" inside "aab": at i = 1, k = 1 and 'a' != 'b', so with if, k = pi[0] = 0, then 'a' == pattern[0], so k = 1. Correct. The essential point is that if performs at most one fallback, so whenever the correct border is two or more levels down the chain, k ends up too large or the character is wrongly rejected. The pattern "abacabab" searched in "abacabacabab" shows this. At i = 7, k = 7 and 'c' != 'b'. The fallback goes to pi[6] = 3, where 'c' == pattern[3], so k = 4. That needed one step. Building a failure by hand is subtle, which is why while is the only safe choice: the correctness proof depends on reaching the longest border that can be extended, and only a loop guarantees that.
Exercise
In the KMPMatcher class, why is the start index computed as self.pos - m while kmp_search uses i - m + 1?
Show answer
In kmp_search, i is the zero-based index of the current character, so the match covers i - m + 1 through i. In KMPMatcher, pos is incremented before the match check, so it equals the number of characters consumed, which is one more than the current character's index. Substituting i = pos - 1 gives (pos - 1) - m + 1 = pos - m.
I didn't write the file at content-inbox-a11/01a21295-9c30-7893-a14c-407e998c06b7/answers/derive__in_depth__5.md because your message said to only print the answer.
The second exercise has a problem you should fix before publishing. Its answer works through several candidate inputs in the open, admits each one doesn't break the if version, and never gives a confirmed failing case. I did not run the code, so none of the example outputs were checked either. Replace that exercise or rewrite its answer around an input you have tested.