29. KMP String Matching
Find a pattern in a text in O(n + m) by never moving backwards in the text. A precomputed prefix table tells the matcher how far to fall back after a mismatch.
How it works
The naive search restarts the pattern at the next text position after every mismatch, which can cost O(n * m). Knuth-Morris-Pratt (KMP) notices that the characters already matched are known, so it can reuse them.
The prefix function lps[i] is the length of the longest proper prefix of pattern[:i + 1] that is also a suffix of it. During the scan, j is how many pattern characters currently match. On a mismatch, set j = lps[j - 1] and try again, instead of restarting at 0. The text index i only moves forward.
Diagram
flowchart TD
A["Compare text at i with pattern at j"] --> B{"Equal?"}
B -->|yes| C["j plus 1, then i plus 1"] --> D{"j equals pattern length?"}
D -->|yes| M["Report match, j = lps at j minus 1"] --> A
D -->|no| A
B -->|"no, j above 0"| F["Fall back: j = lps at j minus 1"] --> A
B -->|"no, j is 0"| G["i plus 1"] --> A
Step-by-step trace
Input: Prefix table for pattern ababc.
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| char | a | b | a | b | c |
| lps | 0 | 0 | 1 | 2 | 0 |
Input: Search ababc in abacababcab.
| i | text[i] | j before | Fallbacks | j after | Event |
|---|---|---|---|---|---|
| 0 | a | 0 | - | 1 | - |
| 1 | b | 1 | - | 2 | - |
| 2 | a | 2 | - | 3 | - |
| 3 | c | 3 | 3->1, 1->0 | 0 | - |
| 4 | a | 0 | - | 1 | - |
| 5 | b | 1 | - | 2 | - |
| 6 | a | 2 | - | 3 | - |
| 7 | b | 3 | - | 4 | - |
| 8 | c | 4 | - | 0 | match at 4 |
| 9 | a | 0 | - | 1 | - |
| 10 | b | 1 | - | 2 | - |
Result: Matches at [4]. At i = 3 the mismatch made j fall back 3->1, 1->0 while i stayed put; the text is never re-read.
Complexity
| Operation | Time | Space |
|---|---|---|
| Prefix function | O(m) | O(m) |
| Search | O(n + m) | O(m) |
| Naive search (worst) | O(n * m) | O(1) |
Python reference implementation
def prefix_function(pattern):
"""lps[i] = length of the longest proper prefix of pattern[:i+1] that is also its suffix."""
lps = [0] * len(pattern)
k = 0
for i in range(1, len(pattern)):
while k and pattern[i] != pattern[k]:
k = lps[k - 1]
if pattern[i] == pattern[k]:
k += 1
lps[i] = k
return lps
def kmp_search(text, pattern):
"""Start indices of every occurrence of pattern in text."""
if not pattern:
return list(range(len(text) + 1))
lps, matches, j = prefix_function(pattern), [], 0
for i, ch in enumerate(text):
while j and ch != pattern[j]:
j = lps[j - 1] # fall back instead of restarting
if ch == pattern[j]:
j += 1
if j == len(pattern):
matches.append(i - j + 1)
j = lps[j - 1]
return matches
Common mistakes and tips
- After a full match, continue with
j = lps[j - 1]so overlapping matches are found. - In Python,
str.findandinare fast for everyday use; KMP matters in interviews and for streaming text. - The prefix function alone solves ‘shortest palindrome’ and ‘repeated substring pattern’ problems.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Monotonic Stack (Next Greater Element) | Next: Recursion and the Call Stack |