A first try
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.
The pointer i walks the text and q counts matched pattern letters. t[0..3] (letters 0 to 3) is ABAB, the same as p[0..3]. After four checks, i = 4 and q = 4. Line 6 tests each letter; every match moves i one place right.
Line 4 finds t[4] is A but p[4] is C: a mismatch. Naive search would slide the pattern one place and send i back to 1, re-reading t[1..3]. KMP keeps i at 4: it already knows those letters were ABAB.
Reusing what we know
ABAB ends in AB and the pattern starts with AB: that overlap is a border. Line 5 slides the pattern 2 places, so q = 2 and i stays. Line 6: t[4] = p[2] = A, so q = 3 and i moves to 5.
Borders depend only on the pattern, so compute them once. fail[j] is the longest border of p[0..j]; for ABABC that is 0, 0, 1, 2, 0. On a mismatch after q matches, q becomes fail[q − 1].
At i = 5, line 4 finds C ≠ p[3], so line 5 sets q = fail[2] = 1. C ≠ p[1] too, so q = fail[0] = 0. Line 6: C ≠ p[0], so i moves on to 6. The pattern slid right.
From i = 6 all five letters match on line 6, and when i reaches 10, q = m = 5, so line 9 returns 6: i − q + 1 = 10 − 5 + 1.
Cost and code
i only moved right: 11 letters, 14 checks. Each check moves i right or slides the pattern right, and each can happen at most n times, so KMP makes at most 2n checks. With the O(m) table, the total is O(n + m).
In Python, the for loop moves i, the while loop falls back through fail, and q counts the match. kmp('ABABACABABC', 'ABABC', [0, 0, 1, 2, 0]) returns 6. The same idea, run on the pattern, builds fail.
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).