Sub topic 12
The KMP Automaton
This chapter assumes you already know the prefix function pi and the KMP search loop from earlier chapters. You should also be comfortable with Python dictionaries and Big-O notation.
From Fallback Loop to Lookup Table
In standard KMP, a mismatch starts a while loop that follows pi links until the pattern can be extended or k reaches 0. That loop is cheap on average, because the total work stays O(n + m). A single text character, though, can trigger many fallback steps.
The KMP automaton removes the loop. It is a deterministic finite automaton (DFA), a machine with a fixed set of states and exactly one transition for each pair of state and input symbol. For a pattern of length m:
- The states are
0, 1, ..., m. Statejmeans "the longest pattern prefix that ends here has lengthj". delta[j][c]is the next state after reading charactercin statej.- Reaching state
mmeans a match ends at the current position.
Every fallback is computed ahead of time, so the search does exactly one table lookup per text character.
Building the Transition Table
The rule follows from the prefix function:
- If
j < mandpattern[j] == c, the match extends:delta[j][c] = j + 1. - Otherwise, if
j == 0, nothing matches:delta[0][c] = 0. - Otherwise, act the same as the state you would fall back to:
delta[j][c] = delta[pi[j - 1]][c].
Rule 3 works because pi[j - 1] < j, so that row is already filled in when you need it. State m uses the same rule, and that is how overlapping matches are found.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def build_automaton(pattern, alphabet):
m = len(pattern)
pi = prefix_function(pattern)
delta = [dict() for _ in range(m + 1)]
for j in range(m + 1):
for c in alphabet:
if j < m and pattern[j] == c:
delta[j][c] = j + 1
elif j == 0:
delta[j][c] = 0
else:
delta[j][c] = delta[pi[j - 1]][c]
return delta
def automaton_search(text, pattern, alphabet):
m = len(pattern)
delta = build_automaton(pattern, alphabet)
state = 0
matches = []
for i, c in enumerate(text):
state = delta[state].get(c, 0)
if state == m:
matches.append(i - m + 1)
return matches
print(automaton_search("abababca", "abab", "abc")) # [0, 2]The .get(c, 0) call handles characters that are not in the alphabet. A character that never appears in the pattern always sends the machine back to state 0, so this default is correct.
The Automaton for "abab"
Tracing "abababca" visits the states 1, 2, 3, 4, 3, 4, 0, 1. State 4 appears at indices 3 and 5, which gives matches starting at 0 and 2. The edge S4 --> S3 : a is the overlap: after a full match, the border "ab" is reused.
Trade-offs: When to Use It
| Aspect | KMP with `pi` | KMP automaton | Column | Column |
|---|---|---|---|---|
| Preprocessing time | O(m) | O(m · \ | Σ\ | ) |
| Extra memory | O(m) | O(m · \ | Σ\ | ) |
| Work per text character | Amortized O(1), worst case O(m) | Exactly O(1) | ||
| Total search time | O(n) | O(n) |
Here \|Σ\| is the size of the alphabet. Prefer the automaton when:
- You need real-time guarantees. Streaming systems, network packet filters, and hardware matchers must handle each byte in bounded time.
- The alphabet is small. DNA uses 4 symbols, and bytes use 256. A table over Unicode code points would be far too large.
- One pattern is run against many texts. The higher build cost is paid once and spread over all the searches.
Exercises
Exercise
Build the full transition table for pattern "aab" over the alphabet {a, b}.
Show answer
pi = [0, 1, 0]. State 0: a→1, b→0. State 1: a→2, b→delta[0][b]=0. State 2: a→delta[pi[1]=1][a]=2, b→3. State 3: a→delta[pi[2]=0][a]=1, b→delta[0][b]=0.
Exercise
Plain KMP and the automaton both run in O(n) total. Why does the automaton still give a stronger guarantee per character?
Show answer
Plain KMP can run its while loop up to O(m) times on one mismatched character, and it only averages out to O(1) across the whole text. The automaton does exactly one table lookup for every character, so no single character takes more than constant time.