TExcelTAD

The Knuth-Morris-Pratt Algorithm

The automaton matcher reads every text character once but needs a table with a row for every character of the alphabet. Knuth, Morris and Pratt (1977, with Morris's version from 1970) found that a single array of mm numbers, the prefix function, contains all the information that matters. When a mismatch happens after qq matched characters, the prefix function says how many of them can be kept. The result is a matcher with Θ(n+m)\Theta(n + m) worst-case time and Θ(m)\Theta(m) extra space, whose analysis is a classic of amortized reasoning.

What a mismatch tells us

Suppose qq characters of the pattern have matched, so the text ends with PqP_q, and the next text character differs from P[q]P[q]. The naive algorithm would shift by one and start over. But we know the last qq text characters: they are PqP_q. The next possible match must start inside this stretch at a position where a prefix of PP is also a suffix of PqP_q. The longest such prefix gives the smallest safe shift.

The prefix function of PP is

π[q]=the length of the longest proper prefix of P that is a suffix of P[0..q],0≤q<m.\pi[q] = \text{the length of the longest proper prefix of } P \text{ that is a suffix of } P[0..q], \qquad 0 \le q < m .

("Proper" means shorter than P[0..q]P[0..q] itself.) For $P = $ ababcab:

qq 0 1 2 3 4 5 6
P[q]P[q] a b a b c a b
π[q]\pi[q] 0 0 1 2 0 1 2

So after matching abab and failing, the algorithm continues as if ab (π[3]=2\pi[3] = 2 characters) had matched, without moving backwards in the text.

The algorithm

text
PREFIX-FUNCTION(P)                       KMP-MATCH(T, P)
1  pi[0] = 0; k = 0                      1  pi = PREFIX-FUNCTION(P); q = 0
2  for q = 1 to m - 1                    2  for i = 0 to n - 1
3      while k > 0 and P[k] != P[q]      3      while q > 0 and P[q] != T[i]
4          k = pi[k - 1]                 4          q = pi[q - 1]          // fall back
5      if P[k] == P[q]                   5      if P[q] == T[i]
6          k = k + 1                     6          q = q + 1
7      pi[q] = k                         7      if q == m
8  return pi                             8          report i - m + 1
                                         9          q = pi[m - 1]

The two procedures are the same loop: computing π\pi is matching the pattern against itself. In both, the variable (kk or qq) is the number of characters currently matched, and the inner while follows the chain π[q−1],π[π[q−1]−1],…\pi[q-1], \pi[\pi[q-1]-1], \ldots of ever shorter prefixes that are also suffixes, until one can be extended or none is left.

The animation computes the prefix function of ababcab and then matches it against a text with two overlapping-looking occurrences.

The program prints the same steps as the animation.

python · try it yourself
def prefix_function(P):
    pi, k = [0] * len(P), 0
    for q in range(1, len(P)):
        while k > 0 and P[k] != P[q]:
            k = pi[k - 1]
        if P[k] == P[q]:
            k += 1
        pi[q] = k
    return pi

def kmp(T, P, verbose=False):
    pi, q, found, comparisons = prefix_function(P), 0, [], 0
    for i, c in enumerate(T):
        while q > 0 and P[q] != c:
            comparisons += 1
            if verbose:
                print(f"  text {i}: {c} != {P[q]}, fall back q = pi[{q - 1}] = {pi[q - 1]}")
            q = pi[q - 1]
        comparisons += 1
        if P[q] == c:
            q += 1
            if verbose:
                print(f"  text {i}: {c} matches pattern {q - 1}, q = {q}")
        elif verbose:
            print(f"  text {i}: {c} != {P[0]}, move on")
        if q == len(P):
            found.append(i - len(P) + 1)
            if verbose:
                print(f"  match at shift {i - len(P) + 1}, continue with q = pi[{len(P) - 1}] = {pi[-1]}")
            q = pi[q - 1]
    return found, comparisons

P = "ababcab"
print("pi =", prefix_function(P))
found, comps = kmp("abababcabababcabc", P, verbose=True)
print("matches at", found, "with", comps, "character comparisons for 17 text characters")
pi = [0, 0, 1, 2, 0, 1, 2]
  text 0: a matches pattern 0, q = 1
  text 1: b matches pattern 1, q = 2
  text 2: a matches pattern 2, q = 3
  text 3: b matches pattern 3, q = 4
  text 4: a != c, fall back q = pi[3] = 2
  text 4: a matches pattern 2, q = 3
  text 5: b matches pattern 3, q = 4
  text 6: c matches pattern 4, q = 5
  text 7: a matches pattern 5, q = 6
  text 8: b matches pattern 6, q = 7
  match at shift 2, continue with q = pi[6] = 2
  text 9: a matches pattern 2, q = 3
  text 10: b matches pattern 3, q = 4
  text 11: a != c, fall back q = pi[3] = 2
  text 11: a matches pattern 2, q = 3
  text 12: b matches pattern 3, q = 4
  text 13: c matches pattern 4, q = 5
  text 14: a matches pattern 5, q = 6
  text 15: b matches pattern 6, q = 7
  match at shift 9, continue with q = pi[6] = 2
  text 16: c != a, fall back q = pi[1] = 0
  text 16: c != a, move on
matches at [2, 9] with 20 character comparisons for 17 text characters

Linear time by amortization

The inner while loop can run many times for one character, so a quick look suggests O(nm)O(nm). The truth is O(n)O(n) for the matcher and O(m)O(m) for the prefix function, by the potential method (The Potential Method) with the potential Φ=q\Phi = q.

  • Every iteration of the inner while loop decreases qq, since π[q−1]<q\pi[q - 1] < q.
  • Each step of the outer loop increases qq by at most 1 (line 6).
  • qq never becomes negative.

So over the whole run, the total number of decreases is at most the total number of increases, which is at most nn. The inner loop runs at most nn times in total, and the matcher makes at most 2n2n character comparisons (one successful or final comparison per character, plus one per fallback). The same argument with kk gives at most 2m2m comparisons for the prefix function. Total: Θ(n+m)\Theta(n + m) time, Θ(m)\Theta(m) space.

Why the fallback chain finds every candidate

The prefixes of PP that are suffixes of P[0..q]P[0..q], from longest to shortest, are Pπ[q]P_{\pi[q]}, Pπ[π[q]−1]P_{\pi[\pi[q] - 1]}, and so on until length 0. Indeed, if PkP_k is a proper prefix that is a suffix of P[0..q]P[0..q] with k<π[q]k < \pi[q], then PkP_k is also a suffix of the longer Pπ[q]P_{\pi[q]}, hence a prefix-suffix of Pπ[q]P_{\pi[q]}, and by induction it appears in the chain from there. So following the chain visits every possible partial match in decreasing order, and the first one that can be extended by the next character is the longest one: the matcher never skips a valid shift.

The program measures the comparisons on texts designed to be hard for the naive algorithm and on random text.

python · try it yourself
import random

def kmp_comparisons(T, P):
    pi, k = [0] * len(P), 0
    for q in range(1, len(P)):
        while k > 0 and P[k] != P[q]:
            k = pi[k - 1]
        if P[k] == P[q]:
            k += 1
        pi[q] = k
    q, comps, found = 0, 0, 0
    for c in T:
        while q > 0 and P[q] != c:
            comps += 1
            q = pi[q - 1]
        comps += 1
        if P[q] == c:
            q += 1
        if q == len(P):
            found += 1
            q = pi[q - 1]
    return comps, found

def naive_comparisons(T, P):
    c = 0
    for s in range(len(T) - len(P) + 1):
        for j in range(len(P)):
            c += 1
            if T[s + j] != P[j]:
                break
    return c

rng = random.Random(6)
cases = [("a" * 3000, "a" * 99 + "b"), ("ab" * 1500, "ab" * 50 + "b"),
         ("".join(rng.choice("ab") for _ in range(3000)), "abbabaabab")]
for T, P in cases:
    kc, found = kmp_comparisons(T, P)
    print(f"n = {len(T)}, m = {len(P):3}: KMP {kc:5} comparisons (<= 2n = {2 * len(T)}), "
          f"naive {naive_comparisons(T, P):6}, matches {found}")
n = 3000, m = 100: KMP  5901 comparisons (<= 2n = 6000), naive 290100, matches 0
n = 3000, m = 101: KMP  4450 comparisons (<= 2n = 6000), naive 147900, matches 0
n = 3000, m =  10: KMP  4471 comparisons (<= 2n = 6000), naive   5951, matches 3

On the repetitive texts the naive algorithm makes 30 to 50 times as many comparisons, and the factor grows with mm; KMP never exceeds 2n2n. On random text both are fast, and KMP gains little: its advantage is the guarantee.

In C++

KMP in C++, returning every occurrence, the function asked for in the practice problem.

cpp · try it yourself
#include <cstdio>
#include <string>
#include <utility>
#include <vector>

std::vector<int> prefix_function(const std::string& P) {
    std::vector<int> pi(P.size(), 0);
    for (size_t q = 1, k = 0; q < P.size(); q++) {
        while (k > 0 && P[k] != P[q]) k = pi[k - 1];
        if (P[k] == P[q]) k++;
        pi[q] = int(k);
    }
    return pi;
}

std::vector<int> find_all(const std::string& T, const std::string& P) {
    std::vector<int> found;
    if (P.empty() || P.size() > T.size()) return found;
    auto pi = prefix_function(P);
    size_t q = 0;
    for (size_t i = 0; i < T.size(); i++) {
        while (q > 0 && P[q] != T[i]) q = pi[q - 1];
        if (P[q] == T[i]) q++;
        if (q == P.size()) { found.push_back(int(i + 1 - P.size())); q = pi[q - 1]; }
    }
    return found;
}

int main() {
    auto pi = prefix_function("ababcab");
    std::printf("pi:");
    for (int v : pi) std::printf(" %d", v);
    std::printf("\n");
    for (auto [T, P] : std::vector<std::pair<std::string, std::string>>{
             {"abababcabababcabc", "ababcab"}, {"aaaaa", "aa"}, {"mississippi", "issi"}, {"abc", "d"}}) {
        std::printf("find_all(\"%s\", \"%s\") =", T.c_str(), P.c_str());
        for (int s : find_all(T, P)) std::printf(" %d", s);
        std::printf("\n");
    }
}
pi: 0 0 1 2 0 1 2
find_all("abababcabababcabc", "ababcab") = 2 9
find_all("aaaaa", "aa") = 0 1 2 3
find_all("mississippi", "issi") = 1 4
find_all("abc", "d") =

Overlapping occurrences are all reported (aa occurs four times in aaaaa, issi twice in mississippi). Practise with Find Every Occurrence (KMP). The prefix function has many other uses: the length of the shortest period of a string is m−π[m−1]m - \pi[m - 1], and running it on P#T (with a separator not in either string) finds the matches as positions where the value reaches mm.

Test yourself

What is the prefix function of aabaaab?

  1. 0 1 0 1 2 2 3
  2. 0 1 0 1 2 3 4
  3. 0 0 1 0 1 2 3
  4. 0 1 2 0 1 2 3

Why does KMP make at most 2n2n character comparisons while matching?

  1. Because the pattern is preprocessed
  2. Each fallback decreases qq, which grows by at most 1 per text character, so there are at most nn fallbacks in total
  3. Because π[q]≤q/2\pi[q] \le q/2
  4. Because it skips half of the text

After reporting a match, what value does KMP give to qq?

  1. 0
  2. mm
  3. π[m−1]\pi[m - 1]
  4. m−1m - 1

What is the space needed by KMP besides the text and the pattern?

  1. Θ(1)\Theta(1)
  2. Θ(m)\Theta(m)
  3. Θ(m∣Σ∣)\Theta(m \lvert \Sigma \rvert)
  4. Θ(n)\Theta(n)