ENع
→KMP search
الدرس 47 · Strings and problem-solving patterns

KMP: never look back

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 47 · تفاعلي
01 / 09

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. Four 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 = 4
  3. A 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 4
  4. Reuse 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 places
  5. The 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 fail
  6. Fall 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 = 0
  7. Match 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 6
  8. Never 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 checks
  9. The 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]

اختبار يتاح بعد الخطوة الأخيرة.