Substring search on repeating text: how does KMP skip ahead?
Question
A naive substring search checks every starting index from scratch. On "a" * 1000 + "b" with pattern "a" * 50 + "b", it runs 48,501 character comparisons because it keeps re-checking the same "a" prefix.
Write kmp_find_all(text, pattern) using the Knuth-Morris-Pratt (KMP) prefix function pi. Return every starting index where pattern appears in text, including overlapping matches, in O(n + m) time.
kmp_find_all("ababababc", "ababc") # [4] kmp_find_all("abababa", "aba") # [0, 2, 4] kmp_find_all("abc", "") # [0, 1, 2, 3]
def kmp_find_all(text, pattern): ...
Show hints (3)
- "REUSE MATCHED PREFIX"
When
textmatches"abab"and then fails on'c', you already know the last two characters are"ab". You do not need to move the text index backward. - "THE PREFIX ARRAY"
For each index
i, storepi[i]: the length of the longest proper prefix ofpattern[:i + 1]that is also a suffix. For"ababc",piis[0, 0, 1, 2, 0]. - "FALLBACK AND OVERLAPS"
On a mismatch with
j > 0, loopj = pi[j - 1]until characters match orjhits 0. After a full match, recordi - len(pattern) + 1and setj = pi[j - 1].
Show checked explanation
Precompute the prefix function pi for pattern in O(m) time, where pi[k] is the longest proper prefix of pattern[:k + 1] that is also its suffix. Then scan text once in O(n) time without moving text pointer i backward. On any mismatch, jump pattern index j to pi[j - 1] and keep going.
def kmp_find_all(text, pattern): if not pattern: return list(range(len(text) + 1)) pi, hits, j = [0] * len(pattern), [], 0 for i in range(1, len(pattern)): while j and pattern[i] != pattern[j]: j = pi[j - 1] pi[i] = j = j + (1 if pattern[i] == pattern[j] else 0) j = 0 for i, ch in enumerate(text): while j and ch != pattern[j]: j = pi[j - 1] j += 1 if ch == pattern[j] else 0 if j == len(pattern): hits.append(i - len(pattern) + 1) j = pi[j - 1] return hits print(kmp_find_all("ababababc", "ababc"), kmp_find_all("abababa", "aba"))
[4] [0, 2, 4]
Code and edge cases run on CPython 3.12.10; official documentation links checked. Checked by an editor other than the author.
Walkthrough
Naive matching throws away what it just read. On "ababababc" with "ababc", it matches "abab", fails at text[4] == 'a' against pattern[4] == 'c', and backs up to index 1. On "a" * 1000 + "b" and "a" * 50 + "b", that backtracking costs 48,501 comparisons, while KMP needs 2,050.
KMP builds the prefix array pi (often called the LPS array) for pattern first. Each pi[k] gives the length of the longest proper prefix of pattern[:k + 1] that also ends pattern[:k + 1]. Here is pi for "ababc":
| index | prefix | matching proper prefix and suffix | pi[k] |
|---|---|---|---|
| 0 | a | none | 0 |
| 1 | ab | none | 0 |
| 2 | aba | a | 1 |
| 3 | abab | ab | 2 |
| 4 | ababc | none | 0 |
Now trace scanning "ababababc". Text index i steps forward one character at a time and never moves back:
- Indices 0 to 3 match
"abab", sojreaches 4. - At
i = 4,text[4]is'a'whilepattern[4]is'c'. Instead of restarting ati = 1, KMP readspi[3] = 2. The last two matched characters are already"ab", sojdrops to 2. Nowtext[4]('a') matchespattern[2]('a'), raisingjto 3. - Index 5 (
'b') raisesjto 4. Index 6 ('a') mismatches'c', falls back toj = pi[3] = 2, and matchespattern[2]('a') to reachj = 3. - Indices 7 (
'b') and 8 ('c') bringjto 5, recording the match at8 - 5 + 1 = 4.
After a full match, j = pi[j - 1] keeps the longest overlapping prefix alive. For "abababa" and "aba", pi is [0, 0, 1], so after matching at index 0, j drops to 1 ("a") and immediately catches the overlaps at 2 and 4.
Building pi takes O(m) time and memory. Scanning text takes O(n) time, giving O(n + m) total.
Common mistakes
- Resetting
j = 0after a full match instead ofj = pi[j - 1]. On"abababa"with"aba", you return[0, 4]and miss the overlapping match at index 2. - Using
ifinstead ofwhileforj = pi[j - 1]. For"aaab",pibecomes[0, 1, 2, 1]instead of[0, 1, 2, 0], giving a false match at index 3 in"aaabaab"("baab"). - Allowing the full substring as a prefix when computing
pi. Everypi[k]would equalk + 1, soj = pi[j - 1]would never shrinkjand thewhileloop would hang. - Forgetting the empty-pattern guard. Without
if not pattern:, comparingch == pattern[0]raisesIndexError.
Follow-up questions
- "Why is the nested while loop still O(n + m) total?" Think of
jas a savings account. Each outer loop step adds at most 1 toj. Everywhileiteration strictly lowersjbecausepi[j - 1] < j, andjnever goes below 0. So thewhileloop runs at mostm - 1times buildingpiand at mostntimes scanningtext. - "How does Python's str.find compare to KMP?" CPython's
str.findruns a fast two-way and Boyer-Moore-Horspool hybrid in C, so usestr.findorinin production Python. KMP shines when input arrives as a byte stream you cannot backtrack over, or when you needpidirectly. - "How can pi tell whether a string is a repeat of a shorter block?" Let
n = len(s)andp = n - pi[-1]. The string repeats a shorter block if and only ifpi[-1] > 0andn % p == 0. For"ababab",n = 6,pi[-1] = 4,p = 2, and6 % 2 == 0.
What a strong answer covers
Explains what pi[k] means on a concrete pattern before coding and keeps text pointer i moving strictly forward. Proves the O(n + m) amortized bound on j, and handles overlapping matches plus an empty pattern.
Open in interactive practice deck →