1. Gyanastra
  2. Algorithms
  3. Knuth-Morris-Pratt Algorithm
  4. The matching algorithm
Free lesson, no account needed 6 min read

Algorithms · Knuth-Morris-Pratt Algorithm

The matching algorithm

k = 0                                  // number of chars matched so far
for i = 0 to n-1:                      // scan text left to right, once
    while k > 0 and T[i] != P[k]:
        k = pi[k-1]                    // shift pattern; text pointer NOT moved back
    if T[i] == P[k]:
        k = k + 1
    if k == m:
        report match at s = i - m + 1
        k = pi[m-1]                    // prepare for possible overlapping match

Key property: the text pointer i never moves backwards. Only the pattern pointer k moves, and it moves left only via π\pi.

6.1 Full trace on a text

Let T=T = abababacaba (n=11n=11), P=P = ababaca (m=7m=7), π=[0,0,1,2,3,0,1]\pi = [0,0,1,2,3,0,1].

stepiiT[i]T[i]kk beforecompare with P[k]P[k]actionkk after
10a0P[0]P[0]=amatch1
21b1P[1]P[1]=bmatch2
32a2P[2]P[2]=amatch3
43b3P[3]P[3]=bmatch4
54a4P[4]P[4]=amatch5
65b5P[5]P[5]=cmismatch → k=π[4]=3k=\pi[4]=3; b vs P[3]P[3]=b match4
76a4P[4]P[4]=amatch5
87c5P[5]P[5]=cmatch6
98a6P[6]P[6]=amatch → k=7=mk=7=m: match at s=8−7+1=2s=8-7+1=2; reset k=π[6]=1k=\pi[6]=11
109b1P[1]P[1]=bmatch2
1110a2P[2]P[2]=amatch3

End of text. One match, at s=2s=2: T[2..8]=T[2..8]= ababaca ✓.

Count the character comparisons: steps 1–5 give 5, step 6 gives 2 (one mismatch + one match), steps 7–9 give 3, steps 10–11 give 2. Total =5+2+3+2=12= 5+2+3+2 = 12 comparisons for n=11n=11, m=7m=7. Naive would have needed more (it would re-scan after the failure at i=5i=5).

6.2 The 2n2n bound

Claim: the matching phase performs at most 2n2n character comparisons.

Proof sketch. Each comparison either (a) succeeds and increments kk, or (b) fails inside the while and decreases kk (to π[k−1]<k\pi[k-1] < k). kk starts at 0, is incremented at most once per text character (so at most nn increments total), and never goes below 0. Hence the number of decrements is at most the number of increments, i.e. ≤n\le n. Total comparisons = (successes) + (failures) ≤n+n=2n\le n + n = 2n. ∎

So matching is O(n)O(n); preprocessing is O(m)O(m); total O(n+m)O(n+m), and the constant is small. Space: O(m)O(m) for π\pi (plus O(1)O(1) working variables).


Borders: the deeper relation

  • π[i]\pi[i] is the length of the longest proper border of P[0..i]P[0..i].
  • The chain of all borders of P[0..i]P[0..i] is: π[i]\pi[i], then π[π[i]−1]\pi[\pi[i]-1], then π[π[π[i]−1]−1]\pi[\pi[\pi[i]-1]-1], … down to 0. This chain is exactly what the while loop walks.
  • A string of length LL has a border of length bb iff P[0..b−1]=P[L−b..L−1]P[0..b-1] = P[L-b..L-1]; the smallest period of PP is L−π[L−1]L - \pi[L-1] (a period need not divide LL).
  • Application (classic GATE-style): the smallest shift that brings a fresh copy of PP into alignment after a full match is m−π[m−1]m - \pi[m-1]; this is why the code resets k=π[m−1]k = \pi[m-1] after reporting a match, which correctly finds overlapping occurrences.

Comparison of string-matching algorithms

nn = text length, mm = pattern length, σ\sigma = alphabet size.

AlgorithmPreprocessing timePreprocessing spaceMatching time (worst)Matching time (expected / typical)Notes
Naive00O(1)O(1)Θ(nm)\Theta(nm)often O(n)O(n)restarts at every shift
Rabin–KarpΘ(m)\Theta(m)O(1)O(1)O(nm)O(nm) (spurious hits)O(n+m)O(n+m)rolling hash; good for multi-pattern
Finite automatonO(mσ)O(m\sigma) (or O(m)O(m) with care)O(mσ)O(m\sigma)Θ(n)\Theta(n)Θ(n)\Theta(n)every char = exactly 1 transition; no fallback loop
KMPΘ(m)\Theta(m)Θ(m)\Theta(m)Θ(n)\Theta(n)Θ(n)\Theta(n)never re-reads text; ≤2n\le 2n comparisons
Boyer–MooreΘ(m+σ)\Theta(m + \sigma)O(m+σ)O(m+\sigma)O(nm)O(nm) worst (basic)sublinear, often O(n/m)O(n/m)compares right-to-left, uses bad-character & good-suffix heuristics

One-line memory hooks: KMP = never move the text pointer back; automaton = KMP with the fallback loop precomputed into a table; Boyer–Moore = skip whole blocks using the right end.


Typical exam question patterns

  1. "Compute the failure/prefix array of pattern XX." → Run the π\pi algorithm left to right; for each ii take the longest proper border of P[0..i]P[0..i]; check the first entry is 0.
  2. "How many character comparisons does KMP make on text TT / pattern PP?" → Trace the matching table above, counting every == test (including the failing ones inside the while).
  3. "Worst-case number of comparisons in KMP matching." → 2n2n (or 2n−12n-1 depending on counting convention); state the bound as O(n)O(n).
  4. "Total time of KMP." → O(n+m)O(n+m); preprocessing O(m)O(m), matching O(n)O(n).
  5. "Which algorithm guarantees linear time with O(m)O(m) extra space?" → KMP (automaton needs O(mσ)O(m\sigma) space).
  6. "Smallest period / shift of a pattern." → m−π[m−1]m - \pi[m-1].
  7. "Number of occurrences / overlapping matches." → After each match reset k=π[m−1]k=\pi[m-1] and continue; count them.
  8. "Compare KMP and naive on T=anT=a^n, P=am−1bP=a^{m-1}b." → Naive Θ(nm)\Theta(nm); KMP Θ(n+m)\Theta(n+m).

Pages 1–2 of 2