download

Substring search on repeating text: how does KMP skip ahead?

Algorithms~15 minReviewed 3 Dec 2026Free · No sign-in

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.

"PYTHON"
kmp_find_all("ababababc", "ababc")  # [4]
kmp_find_all("abababa", "aba")      # [0, 2, 4]
kmp_find_all("abc", "")             # [0, 1, 2, 3]
"CODE · PYTHON"
def kmp_find_all(text, pattern):
    ...
Show hints (3)
  1. "REUSE MATCHED PREFIX"

    When text matches "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.

  2. "THE PREFIX ARRAY"

    For each index i, store pi[i]: the length of the longest proper prefix of pattern[:i + 1] that is also a suffix. For "ababc", pi is [0, 0, 1, 2, 0].

  3. "FALLBACK AND OVERLAPS"

    On a mismatch with j > 0, loop j = pi[j - 1] until characters match or j hits 0. After a full match, record i - len(pattern) + 1 and set j = 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.

"SOLUTION · PYTHON"
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"))
"OUTPUT"
[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":

indexprefixmatching proper prefix and suffixpi[k]
0anone0
1abnone0
2abaa1
3ababab2
4ababcnone0

Now trace scanning "ababababc". Text index i steps forward one character at a time and never moves back:

  • Indices 0 to 3 match "abab", so j reaches 4.
  • At i = 4, text[4] is 'a' while pattern[4] is 'c'. Instead of restarting at i = 1, KMP reads pi[3] = 2. The last two matched characters are already "ab", so j drops to 2. Now text[4] ('a') matches pattern[2] ('a'), raising j to 3.
  • Index 5 ('b') raises j to 4. Index 6 ('a') mismatches 'c', falls back to j = pi[3] = 2, and matches pattern[2] ('a') to reach j = 3.
  • Indices 7 ('b') and 8 ('c') bring j to 5, recording the match at 8 - 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 = 0 after a full match instead of j = pi[j - 1]. On "abababa" with "aba", you return [0, 4] and miss the overlapping match at index 2.
  • Using if instead of while for j = pi[j - 1]. For "aaab", pi becomes [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. Every pi[k] would equal k + 1, so j = pi[j - 1] would never shrink j and the while loop would hang.
  • Forgetting the empty-pattern guard. Without if not pattern:, comparing ch == pattern[0] raises IndexError.

Follow-up questions

  • "Why is the nested while loop still O(n + m) total?" Think of j as a savings account. Each outer loop step adds at most 1 to j. Every while iteration strictly lowers j because pi[j - 1] < j, and j never goes below 0. So the while loop runs at most m - 1 times building pi and at most n times scanning text.
  • "How does Python's str.find compare to KMP?" CPython's str.find runs a fast two-way and Boyer-Moore-Horspool hybrid in C, so use str.find or in in production Python. KMP shines when input arrives as a byte stream you cannot backtrack over, or when you need pi directly.
  • "How can pi tell whether a string is a repeat of a shorter block?" Let n = len(s) and p = n - pi[-1]. The string repeats a shorter block if and only if pi[-1] > 0 and n % p == 0. For "ababab", n = 6, pi[-1] = 4, p = 2, and 6 % 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 →

Original OfferVibe question. NIST DADS: Knuth-Morris-Pratt algorithm · Python str.find.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.