1def kmp(t, p, fail):2 q = 03 for i, c in enumerate(t):4 while q > 0 and c != p[q]:5 q = fail[q - 1]6 if c == p[q]:7 q += 18 if q == len(p):9 return i - q + 110 return -1TEXTt[0]At[1]Bt[2]At[3]Bt[4]At[5]Ct[6]At[7]Bt[8]At[9]Bt[10]Cfail[0]fail[1]fail[2]fail[3]fail[4]AABABAABABABABCi0q0checks0p[0]Ap[1]Bp[2]Ap[3]Bp[4]Cii
Khaki cells: the text; mint tray: the pattern, sliding rightBlue cells: the failure table fail[j]Rose pointer i: the next text letter, only ever moving rightThe rose pointer i reads the text ABABACABABC left to right and never moves back. The mint pattern ABABC slides right under it: on a mismatch after q matches it moves so that its first fail[q − 1] letters sit under the text letters just read. The search finds the pattern at 6 after 14 checks; naive search needs 19 here.

A first try

  1. Search for the pattern ABABC (length m = 5) in the text ABABACABABC (length n = 11). Naive string search re-reads text letters after every mismatch. KMP reads forward only: its text pointer never moves back.

Reusing what we know

Cost and code

What happens

;; step 1/9 · setup
text t = 'ABABACABABC'   n = 11
pattern p = 'ABABC'   m = 5

 i    0  1  2  3  4  5  6  7  8  9 10
 t    A  B  A  B  A  C  A  B  A  B  C

i: the next text letter to read
q: how many pattern letters match so far
the pattern sits under the text starting at i − q

One check is one comparison of a text letter with a pattern letter. In the code, line 4 tests the same pair again on line 6 when the while loop stops on a match, so the figure counts a run of line 5 or line 6 as one check: 14 here. The 2n bound: each match moves i right (at most n times) and each fallback moves the pattern start i − q right (at most n times). CLRS chapter 32 proves the matcher is Θ(n) after Θ(m) preprocessing, so KMP runs in O(n + m).