1. Gyanastra
  2. Algorithms
  3. Knuth-Morris-Pratt Algorithm
  4. The problem, and why naive search is wasteful
Free lesson, no account needed 6 min read

Algorithms · Knuth-Morris-Pratt Algorithm

The problem, and why naive search is wasteful

We are given a text TT of length nn and a pattern PP of length mm (m≤nm \le n). We must report every position ss (0≤s≤n−m0 \le s \le n-m) such that T[s..s+m−1]=P[0..m−1]T[s..s+m-1] = P[0..m-1].

The naive algorithm tries every shift ss and compares characters left to right. When a mismatch occurs at P[j]P[j] vs T[s+j]T[s+j], it throws away everything it learned and restarts at s+1s+1, j=0j=0. Worst case: T=aaa…aT = aaa\ldots a, P=aa…abP = aa\ldots ab, giving Θ(nm)\Theta(nm) comparisons.

The KMP idea: when a mismatch happens after matching P[0..j−1]P[0..j-1], the text characters T[s..s+j−1]T[s..s+j-1] are known to equal P[0..j−1]P[0..j-1]. So instead of shifting by 1, we shift the pattern to the next position where its own prefix matches a suffix of what we already matched. That shift amount depends only on the pattern, so it can be precomputed once.


2.1 Border (definition)

A border of a string XX is a string that is both a proper prefix and a proper suffix of XX ("proper" = shorter than XX).

Example: X=X = ababa. Proper prefixes: a, ab, aba, abab. Proper suffixes: a, ba, aba, baba. Common ones: a and aba. Longest border = aba, length 3.

2.2 Prefix function π\pi (a.k.a. failure function)

For pattern PP of length mm, define for each ii with 0≤i<m0 \le i < m:

π[i]=length of the longest proper border of P[0..i]\pi[i] = \text{length of the longest proper border of } P[0..i]

with the convention π[0]=0\pi[0] = 0 (a single character has no proper border).

Convention warning (this is the #1 trap). Two indexing styles appear in books and exams:

StyleArray nameIndicesMeaning of entry kkUsed by
0-basedπ\pi or lps0…m−10 \ldots m-1longest border of P[0..k]P[0..k]most code (lps), most GATE questions
1-basedff or failure (CLRS: π[1..m]\pi[1..m])1…m1 \ldots mlongest border of P[1..k]P[1..k]; f[1]=0f[1]=0CLRS, Horowitz–Sahni, some UGC-NET

The two are related by f[k+1]=π[k]f[k+1] = \pi[k] for 0≤k<m0 \le k < m. The list of values is the same in both styles (f[k+1]=π[k]f[k+1]=\pi[k]); only the index origin differs. A third variant, the next array of some Indian-syllabus textbooks, is next[j]=f[j−1]+1\text{next}[j]=f[j-1]+1 with next[1]=0\text{next}[1]=0 (for ababaca: [0,1,1,2,3,4,1][0,1,1,2,3,4,1]). Read the question's definition before matching an answer choice.

2.3 The recurrence

π[i]=max⁡{ k+1  :  k∈{π[i−1], π[π[i−1]−1], …, 0} and P[k]=P[i] },π[i]=0 if no such k.\pi[i] = \max\{\,k+1 \;:\; k\in\{\pi[i-1],\ \pi[\pi[i-1]-1],\ \dots,\ 0\}\text{ and } P[k]=P[i]\,\},\qquad \pi[i]=0 \text{ if no such } k.

In words: the longest border of P[0..i]P[0..i] is obtained by extending the longest border of P[0..i−1]P[0..i-1] by one character, if that character matches; otherwise fall back to the border of the border, and so on.

2.4 The algorithm (compute π\pi)

pi[0] = 0
k = 0                       // length of current border
for i = 1 to m-1:
    while k > 0 and P[i] != P[k]:
        k = pi[k-1]         // fall back to border of border
    if P[i] == P[k]:
        k = k + 1
    pi[i] = k

Why it is linear: k increases by at most 1 per iteration of i, so over m−1m-1 iterations it increases at most m−1m-1 times; every while iteration decreases k by at least 1, so total while iterations ≤m−1\le m-1. Total work O(m)O(m).


Worked example 1: P=P = `ababaca`

Write the pattern with 0-based indices:

ii0123456
P[i]P[i]ababaca

Trace:

  • i=0i=0: π[0]=0\pi[0]=0.
  • i=1i=1, P[1]=P[1]= b, k=0k=0: compare b vs P[0]=P[0]= a → no match, kk stays 0. π[1]=0\pi[1]=0.
  • i=2i=2, P[2]=P[2]= a, k=0k=0: a vs a → match, k=1k=1. π[2]=1\pi[2]=1. (border a)
  • i=3i=3, P[3]=P[3]= b, k=1k=1: b vs P[1]=P[1]= b → match, k=2k=2. π[3]=2\pi[3]=2. (border ab)
  • i=4i=4, P[4]=P[4]= a, k=2k=2: a vs P[2]=P[2]= a → match, k=3k=3. π[4]=3\pi[4]=3. (border aba)
  • i=5i=5, P[5]=P[5]= c, k=3k=3: c vs P[3]=P[3]= b → mismatch. Fall back: k=π[2]=1k=\pi[2]=1. Now c vs P[1]=P[1]= b → mismatch. Fall back: k=π[0]=0k=\pi[0]=0. Now c vs P[0]=P[0]= a → mismatch, k=0k=0. π[5]=0\pi[5]=0.
  • i=6i=6, P[6]=P[6]= a, k=0k=0: a vs a → match, k=1k=1. π[6]=1\pi[6]=1.

Result: π=[0,0,1,2,3,0,1]\pi = [0, 0, 1, 2, 3, 0, 1].

Sanity check on i=4i=4: P[0..4]=P[0..4]= ababa; longest proper border is aba (length 3). ✓


Worked example 2: P=P = `aabaab`

ii012345
P[i]P[i]aabaab
  • i=0i=0: π[0]=0\pi[0]=0.
  • i=1i=1, P[1]=P[1]= a, k=0k=0: a vs a → match, k=1k=1. π[1]=1\pi[1]=1. (border a)
  • i=2i=2, P[2]=P[2]= b, k=1k=1: b vs P[1]=P[1]= a → mismatch. Fall back k=π[0]=0k=\pi[0]=0. b vs P[0]=P[0]= a → mismatch. π[2]=0\pi[2]=0.
  • i=3i=3, P[3]=P[3]= a, k=0k=0: a vs a → match, k=1k=1. π[3]=1\pi[3]=1.
  • i=4i=4, P[4]=P[4]= a, k=1k=1: a vs P[1]=P[1]= a → match, k=2k=2. π[4]=2\pi[4]=2. (border aa)
  • i=5i=5, P[5]=P[5]= b, k=2k=2: b vs P[2]=P[2]= b → match, k=3k=3. π[5]=3\pi[5]=3. (border aab)

Result: π=[0,1,0,1,2,3]\pi = [0, 1, 0, 1, 2, 3].

Check i=5i=5: P[0..5]=P[0..5]= aabaab; prefix aab = suffix aab. ✓


Worked example 3: P=P = `abcabcabd`

ii012345678
P[i]P[i]abcabcabd
  • i=0i=0: π[0]=0\pi[0]=0.
  • i=1i=1, b vs a → mismatch, k=0k=0. π[1]=0\pi[1]=0.
  • i=2i=2, c vs a → mismatch, k=0k=0. π[2]=0\pi[2]=0.
  • i=3i=3, a vs a → match, k=1k=1. π[3]=1\pi[3]=1.
  • i=4i=4, b vs P[1]=P[1]= b → match, k=2k=2. π[4]=2\pi[4]=2.
  • i=5i=5, c vs P[2]=P[2]= c → match, k=3k=3. π[5]=3\pi[5]=3.
  • i=6i=6, a vs P[3]=P[3]= a → match, k=4k=4. π[6]=4\pi[6]=4.
  • i=7i=7, b vs P[4]=P[4]= b → match, k=5k=5. π[7]=5\pi[7]=5.
  • i=8i=8, d vs P[5]=P[5]= c → mismatch. Fall back k=π[4]=2k=\pi[4]=2. d vs P[2]=P[2]= c → mismatch. Fall back k=π[1]=0k=\pi[1]=0. d vs P[0]=P[0]= a → mismatch. π[8]=0\pi[8]=0.

Result: π=[0,0,0,1,2,3,4,5,0]\pi = [0, 0, 0, 1, 2, 3, 4, 5, 0].

Check i=7i=7: P[0..7]=P[0..7]= abcabcab; border abcab (length 5). ✓


Pages 1–2 of 2