Algorithms · Knuth-Morris-Pratt Algorithm
The problem, and why naive search is wasteful
We are given a text of length and a pattern of length (). We must report every position () such that .
The naive algorithm tries every shift and compares characters left to right. When a mismatch occurs at vs , it throws away everything it learned and restarts at , . Worst case: , , giving comparisons.
The KMP idea: when a mismatch happens after matching , the text characters are known to equal . 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 is a string that is both a proper prefix and a proper suffix of ("proper" = shorter than ).
Example: 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 (a.k.a. failure function)
For pattern of length , define for each with :
with the convention (a single character has no proper border).
Convention warning (this is the #1 trap). Two indexing styles appear in books and exams:
| Style | Array name | Indices | Meaning of entry | Used by |
|---|---|---|---|---|
| 0-based | or lps | longest border of | most code (lps), most GATE questions | |
| 1-based | or failure (CLRS: ) | longest border of ; | CLRS, Horowitz–Sahni, some UGC-NET |
The two are related by for . The list of values is the same in both styles (); only the index origin differs. A third variant, the next array of some Indian-syllabus textbooks, is with (for ababaca: ). Read the question's definition before matching an answer choice.
2.3 The recurrence
In words: the longest border of is obtained by extending the longest border of 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[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 iterations it increases at most times; every while iteration decreases k by at least 1, so total while iterations . Total work .
Worked example 1: `ababaca`
Write the pattern with 0-based indices:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| a | b | a | b | a | c | a |
Trace:
- : .
- , b, : compare b vs a → no match, stays 0. .
- , a, : a vs a → match, . . (border
a) - , b, : b vs b → match, . . (border
ab) - , a, : a vs a → match, . . (border
aba) - , c, : c vs b → mismatch. Fall back: . Now c vs b → mismatch. Fall back: . Now c vs a → mismatch, . .
- , a, : a vs a → match, . .
Result: .
Sanity check on : ababa; longest proper border is aba (length 3). ✓
Worked example 2: `aabaab`
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| a | a | b | a | a | b |
- : .
- , a, : a vs a → match, . . (border
a) - , b, : b vs a → mismatch. Fall back . b vs a → mismatch. .
- , a, : a vs a → match, . .
- , a, : a vs a → match, . . (border
aa) - , b, : b vs b → match, . . (border
aab)
Result: .
Check : aabaab; prefix aab = suffix aab. ✓
Worked example 3: `abcabcabd`
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|---|
| a | b | c | a | b | c | a | b | d |
- : .
- , b vs a → mismatch, . .
- , c vs a → mismatch, . .
- , a vs a → match, . .
- , b vs b → match, . .
- , c vs c → match, . .
- , a vs a → match, . .
- , b vs b → match, . .
- , d vs c → mismatch. Fall back . d vs c → mismatch. Fall back . d vs a → mismatch. .
Result: .
Check : abcabcab; border abcab (length 5). ✓