KMP: never look back
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Naive string search re-reads text letters every time a partial match fails. The Knuth-Morris-Pratt algorithm (KMP) never does: after a mismatch it already knows the letters it just read, so it slides the pattern to the longest overlap that could still match and keeps reading forward. Watch KMP find ABABC in ABABACABABC with a pointer that only moves right, build the failure table that drives the slides, and see why the whole search takes O(n + m) time. The lesson "Naive string search" covers the slow method this one improves, and the Software lessons "Strings: text in memory" and "Searching: linear and binary" cover strings and searching.
Find ABABC in the text
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.
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
اقرأ الدرس خطوة بخطوة
Find ABABC in the text
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.
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 − qFour matches
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.
i letters result 0 A vs p[0] = A match → i = 1, q = 1 1 B vs p[1] = B match → i = 2, q = 2 2 A vs p[2] = A match → i = 3, q = 3 3 B vs p[3] = B match → i = 4, q = 4A mismatch at i = 4
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.
i letters result 4 A vs p[4] = C mismatch → i = 4, q = 4 naive search: start again at 1, i goes back from 4 to 1 KMP: t[0..3] = p[0..3] = ABAB is already known, i stays at 4Reuse the overlap
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.
matched so far: ABAB (q = 4) prefixes A AB ABA suffixes B AB BAB longest border: AB, length 2 = fail[3] fall back: q = fail[3] = 2, pattern starts at 2 4 A vs p[2] = A match → i = 5, q = 3 slide = q − fail[q − 1] = 4 − 2 = 2 placesThe failure table
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].
j p[0..j] longest border fail[j] 0 A (none) 0 1 AB (none) 0 2 ABA A 1 3 ABAB AB 2 4 ABABC (none) 0 built in O(m) by the same idea, run on the pattern: def build_fail(p): fail = [0] * len(p) k = 0 for j in range(1, len(p)): while k > 0 and p[j] != p[k]: k = fail[k - 1] if p[j] == p[k]: k += 1 fail[j] = k return failFall back to zero
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.
i letters result 5 C vs p[3] = B mismatch → i = 5, q = 3 fall back: q = fail[2] = 1, pattern starts at 4 5 C vs p[1] = B mismatch → i = 5, q = 1 fall back: q = fail[0] = 0, pattern starts at 5 5 C vs p[0] = A mismatch → i = 6, q = 0Match at 6
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.
i letters result 6 A vs p[0] = A match → i = 7, q = 1 7 B vs p[1] = B match → i = 8, q = 2 8 A vs p[2] = A match → i = 9, q = 3 9 B vs p[3] = B match → i = 10, q = 4 10 C vs p[4] = C match → i = 10, q = 5 q = 5 = len(p): match at 6 kmp('ABABACABABC', 'ABABC', [0, 0, 1, 2, 0]) returns 6Never look back
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).
KMP on this text: 14 checks (11 on line 6, 3 fallbacks on line 5) naive on this text: 19 checks bound: checks ≤ 2n = 22 why: a match moves i right; a fallback moves the pattern start (i − q) right; both stop by n worst case, text AAAA…A, pattern AA…AB: naive (n − m + 1)·m checks KMP at most 2n checksThe code
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.
def kmp(t, p, fail): q = 0 for i, c in enumerate(t): while q > 0 and c != p[q]: q = fail[q - 1] if c == p[q]: q += 1 if q == len(p): return i - q + 1 return -1 print(kmp('ABABACABABC', 'ABABC', build_fail('ABABC'))) # 6 build_fail('ABABC') == [0, 0, 1, 2, 0]
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What is the failure table fail for the pattern AABAA?
fail[j] is the longest proper prefix of AABAA[0..j] that is also a suffix: A → 0, AA → 1 (A), AAB → 0, AABA → 1 (A), AABAA → 2 (AA).
02KMP has matched q = 4 letters of ABABC when the next text letter does not match p[4]. With fail = [0, 0, 1, 2, 0], what happens?
The four letters just read were ABAB. Its longest border is AB, so the pattern slides until its AB sits under them: q = fail[q − 1] = fail[3] = 2. i never moves back.
03Why does KMP make at most 2n checks on a text of length n?
A match (or a mismatch with q = 0) moves i right; a fallback moves the pattern start i − q right. Both only grow and stop by n, so the total is at most 2n. A letter can be compared more than once, as t[5] is here (3 times).
04In the lesson's run, how many checks does KMP make, and how many does naive search make on the same text?
KMP: 11 letters, each ending with one test on line 6, plus 3 fallbacks on line 5 = 14. Naive search tries starts 0 to 6 and compares until a mismatch: 5 + 1 + 4 + 1 + 2 + 1 + 5 = 19.
05What is the total running time of KMP for a text of length n and a pattern of length m?
Building the failure table is O(m) by the same amortised argument, and the search is O(n), so KMP is O(n + m). Naive search can need (n − m + 1)·m checks.
المسرد
- Pattern (p)
- The string you are looking for. Its length is m.
- Text (t)
- The string you search in. Its length is n.
- Border
- A string that is both a proper prefix and a suffix of another string. AB is a border of ABAB.
- Failure table (fail)
- fail[j] is the length of the longest border of p[0..j]. CLRS calls it the prefix function π.
- Fallback
- On a mismatch after q matched letters, KMP sets q to fail[q − 1], which slides the pattern right without moving the text pointer.
- Check
- One comparison of a text letter with a pattern letter.
- Naive string search
- Try every starting position and compare letters until one differs: up to (n − m + 1)·m checks.
الملاحظات والمصادر
- 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).
- Naive search tries every start and compares until a mismatch, up to (n − m + 1)·m checks. On this text it needs 19; on a text of n A's with the pattern AA…AB it needs exactly (n − m + 1)·m, while KMP stays within 2n.
- CLRS calls the failure table the prefix function π and indexes from 1. Sedgewick and Wayne build KMP as a finite-state machine instead; the idea, never backing up in the text, is the same.
- The code is real Python 3: kmp('ABABACABABC', 'ABABC', build_fail('ABABC')) returns 6, the same answer as 'ABABACABABC'.find('ABABC').
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 32 String Matching, §32.4 The Knuth-Morris-Pratt algorithm
- Sedgewick and Wayne, Algorithms 4th ed., §5.3 Substring Search
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 9: string matching and the simple algorithm
- MIT 6.047 Computational Biology (Fall 2015), Lecture 3: linear-time exact string matching (Knuth-Morris-Pratt)
- Python documentation: enumerate()
اختبار يتاح بعد الخطوة الأخيرة.