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 .
6.1 Full trace on a text
Let abababacaba (), ababaca (), .
| step | before | compare with | action | after | ||
|---|---|---|---|---|---|---|
| 1 | 0 | a | 0 | =a | match | 1 |
| 2 | 1 | b | 1 | =b | match | 2 |
| 3 | 2 | a | 2 | =a | match | 3 |
| 4 | 3 | b | 3 | =b | match | 4 |
| 5 | 4 | a | 4 | =a | match | 5 |
| 6 | 5 | b | 5 | =c | mismatch → ; b vs =b match | 4 |
| 7 | 6 | a | 4 | =a | match | 5 |
| 8 | 7 | c | 5 | =c | match | 6 |
| 9 | 8 | a | 6 | =a | match → : match at ; reset | 1 |
| 10 | 9 | b | 1 | =b | match | 2 |
| 11 | 10 | a | 2 | =a | match | 3 |
End of text. One match, at : 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 comparisons for , . Naive would have needed more (it would re-scan after the failure at ).
6.2 The bound
Claim: the matching phase performs at most character comparisons.
Proof sketch. Each comparison either (a) succeeds and increments , or (b) fails inside the while and decreases (to ). starts at 0, is incremented at most once per text character (so at most increments total), and never goes below 0. Hence the number of decrements is at most the number of increments, i.e. . Total comparisons = (successes) + (failures) . ∎
So matching is ; preprocessing is ; total , and the constant is small. Space: for (plus working variables).
Borders: the deeper relation
- is the length of the longest proper border of .
- The chain of all borders of is: , then , then , … down to 0. This chain is exactly what the
whileloop walks. - A string of length has a border of length iff ; the smallest period of is (a period need not divide ).
- Application (classic GATE-style): the smallest shift that brings a fresh copy of into alignment after a full match is ; this is why the code resets after reporting a match, which correctly finds overlapping occurrences.
Comparison of string-matching algorithms
= text length, = pattern length, = alphabet size.
| Algorithm | Preprocessing time | Preprocessing space | Matching time (worst) | Matching time (expected / typical) | Notes |
|---|---|---|---|---|---|
| Naive | often | restarts at every shift | |||
| Rabin–Karp | (spurious hits) | rolling hash; good for multi-pattern | |||
| Finite automaton | (or with care) | every char = exactly 1 transition; no fallback loop | |||
| KMP | never re-reads text; comparisons | ||||
| Boyer–Moore | worst (basic) | sublinear, often | 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
- "Compute the failure/prefix array of pattern ." → Run the algorithm left to right; for each take the longest proper border of ; check the first entry is 0.
- "How many character comparisons does KMP make on text / pattern ?" → Trace the matching table above, counting every
==test (including the failing ones inside thewhile). - "Worst-case number of comparisons in KMP matching." → (or depending on counting convention); state the bound as .
- "Total time of KMP." → ; preprocessing , matching .
- "Which algorithm guarantees linear time with extra space?" → KMP (automaton needs space).
- "Smallest period / shift of a pattern." → .
- "Number of occurrences / overlapping matches." → After each match reset and continue; count them.
- "Compare KMP and naive on , ." → Naive ; KMP .