How Knuth-Morris-Pratt skips with the prefix table

Short answer: The Knuth-Morris-Pratt algorithm scans a text for a pattern in O(n + m) time. It builds a prefix table π, where π[i] is the longest proper prefix of the pattern that is also a suffix of the pattern ending at i. When a mismatch occurs after i matched characters, the next comparison resumes at π[i] instead of at the start of the pattern. The text index never moves backward.


What the problem actually asks

A naive scan shifts the pattern by one character after every mismatch and can reexamine a text character as many times as the pattern is long, which is Θ(nm). The characters already matched are a string that is a prefix of the pattern. Any shift that still leaves a match must place a prefix of the pattern over a suffix of that matched string. The longest such prefix is exactly the information the next alignment needs, and it depends only on the pattern.

The prefix table is computed by the same automaton running on the pattern itself. It is not a scan of every substring.


What the algorithm guarantees

The table has length m and is built in O(m) comparisons. The scan of a text of length n performs O(n) comparisons, because the text index only increases and the pattern index increases at most n times and decreases in a way that is charged to those increases. Extra memory is the table. The algorithm reports every match, including overlaps. A match that ends at text position t starts at t − m.

The failure link is not the same object as the Z-box, although both are linear pattern automata. KMP’s link is a border length. The Z-algorithm’s value is the length of a prefix match starting at a position. Either one can search. KMP is the one that never rewinds the text.


The working steps

  1. Build π for the pattern. Set π[0] = 0. For each later index i, start from the border length of i−1 and follow failure links until the next pattern character matches position i, or the length hits 0. Store that new border length.
  2. Set the pattern cursor q = 0. For each text character, follow π while q > 0 and the character does not match pattern[q], assigning q = π[q−1] with the usual 0-based adjustment.
  3. If the character matches, increment q. If q reaches m, report a match ending here and set q = π[m−1] so overlaps are still found.
  4. Do not decrement the text index.
  5. A missing match is the scan finishing with no time q reached m.

The linear bound is for a fixed pattern in a text, in the worst case, with no hashing. It does not filter approximate matches. A Boyer-Moore scan can skip characters in the text and has a worse worst case. Rabin-Karp hashes windows and must verify candidates. KMP is the deterministic linear scan that reuses borders.


Approaches that look simpler and fail

Approach Why it fails when the pattern restarts at zero after every mismatch
Shift the pattern by one and rescan That is the naive algorithm. Its worst case is Θ(nm), which the prefix table exists to avoid.
Set the next q to π[q] without the index adjustment the table was built with Off-by-one in the failure link skips a legal border or loops. The table’s definition and the lookup have to use the same indexing.
Move the text index backward to the start of the last attempt The matched prefix already accounts for every text character just read. Rewinding reintroduces the quadratic comparisons.
Use the table computed for a different pattern The borders are properties of the pattern. A new pattern needs a new table, still in O(m).

A hash of each window is Rabin-Karp. A skip driven by the last mismatched text character is Boyer-Moore. A set of patterns, rather than one, is Aho-Corasick, which generalizes the same failure links to a trie.


A working example

This Python fragment builds the KMP prefix table and never retreats the text index. It prints the starting indexes of aba inside abacaba, 0 4.

def prefix(pat):
    pi = [0] * len(pat)
    k = 0
    for i in range(1, len(pat)):
        while k and pat[k] != pat[i]:
            k = pi[k - 1]
        if pat[k] == pat[i]:
            k += 1
        pi[i] = k
    return pi

def search(text, pat):
    pi = prefix(pat)
    hits, q = [], 0
    for i, ch in enumerate(text):
        while q and pat[q] != ch:
            q = pi[q - 1]
        if pat[q] == ch:
            q += 1
        if q == len(pat):
            hits.append(i - len(pat) + 1)
            q = pi[q - 1]
    return hits

assert search("abacaba", "aba") == [0, 4]
print(*search("abacaba", "aba"))

Where it is used

The Knuth-Morris-Pratt prefix table is the failure function of an exact scanner that preprocesses a pattern once and then streams a long text, such as a log or a DNA string. Boyer-Moore skips more on natural-language text. Many patterns at once are Aho-Corasick.


When you can drop this algorithm

Drop KMP when the practical text is long, the pattern is short, and a tuned Boyer-Moore or a library search already skips ahead. Keep KMP when the worst case must be linear, overlaps matter, and the text cursor must move only forward.


Why this stays published

We publish this so a search for Knuth-Morris-Pratt returns the prefix table and the guarantee that the text index never retreats. Knuth-Morris-Pratt finds every occurrence of a pattern in O(n + m) time by resuming at the longest matched border, without moving the text index backward.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *