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 be comfortable with Python dictionaries and lists, and with Big-O notation.
The KMP search loop does a variable amount of work per text character. One character may cause no fallbacks, and the next may cause several k = pi[k - 1] steps before the loop settles. The amortized total is still O(n), but some applications need a fixed amount of work for every character. The KMP automaton gives you that. It precomputes every fallback chain into a table, so the search does exactly one table lookup per character.
From Fallback Chains to a Transition Table
A deterministic finite automaton (DFA) is a machine with a finite set of states and a transition function. The transition function says which state comes next, given the current state and one input character. The machine reads the input one character at a time and makes exactly one transition per character.
The KMP search loop already behaves like a state machine. Its state is k, the length of the longest pattern prefix that ends at the current text position. When a character c arrives, the loop computes a new k from the old k and c. Nothing else matters: the earlier text characters are fully summarized by k. Because the next state depends only on (k, c), we can compute the answer for every pair ahead of time.
The automaton for a pattern p of length m has:
- States
0, 1, ..., m. Stateqmeans "the lastqcharacters read equalp[0..q-1], and no longer prefix ofpends here." - A start state
0, meaning no characters have matched yet. - One accepting state
m. Reaching it means a full occurrence ofpends at the current position. - A transition function
delta[q][c], defined for each state and each character of the alphabet.
The Transition Recurrence
The table can be filled from the prefix function with this rule:
- If
q < mandp[q] == c, the match extends:delta[q][c] = q + 1. - Otherwise, if
q == 0, nothing matches:delta[0][c] = 0. - Otherwise, fall back to the longest proper border and reuse its row:
delta[q][c] = delta[pi[q - 1]][c].
Rule 3 does the main work. In plain KMP, a mismatch at state q jumps to pi[q - 1] and tries again, and that may repeat. In the automaton, the row for pi[q - 1] already contains the final result of the whole chain, so one lookup replaces the loop. Since pi[q - 1] < q, building rows in increasing order of q means the needed row always exists.
State m follows rule 3 as well, because rule 1 never applies once the whole pattern has matched. This is the automaton's version of resetting k = pi[m - 1] after a match. It is the reason overlapping occurrences are found.
Implementation
The code below is self-contained. It repeats prefix_function from the earlier chapter so that you can run it directly.
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_kmp_automaton(pattern, alphabet):
"""Return delta, a list of m + 1 dicts mapping character -> next state."""
m = len(pattern)
if m == 0:
raise ValueError("pattern must be non-empty")
pi = prefix_function(pattern)
delta = [dict() for _ in range(m + 1)]
for q in range(m + 1):
for c in alphabet:
if q < m and pattern[q] == c:
delta[q][c] = q + 1
elif q == 0:
delta[q][c] = 0
else:
delta[q][c] = delta[pi[q - 1]][c]
return delta
def automaton_search(text, pattern):
m = len(pattern)
delta = build_kmp_automaton(pattern, set(pattern))
matches = []
q = 0
for i, c in enumerate(text):
q = delta[q].get(c, 0) # exactly one lookup per character
if q == m:
matches.append(i - m + 1)
return matches
print(automaton_search("abababca", "abab")) # [0, 2]
print(automaton_search("aaa", "aa")) # [0, 1]
print(automaton_search("xyz", "abab")) # []The alphabet passed to the builder is only set(pattern). A text character that does not appear in the pattern cannot end any prefix of the pattern, so from every state it leads to state 0. The .get(c, 0) default handles those characters without storing them. The table then has m + 1 rows and at most as many columns as the pattern has distinct characters, however large the text's alphabet is.
A Worked Example: Pattern "abab"
The prefix function of "abab" is [0, 0, 1, 2]. Applying the recurrence one row at a time gives this table:
| State q | Meaning (matched prefix) | on 'a' | on 'b' | any other |
|---|---|---|---|---|
| 0 | "" | 1 | 0 | 0 |
| 1 | "a" | 1 | 2 | 0 |
| 2 | "ab" | 3 | 0 | 0 |
| 3 | "aba" | 1 | 4 | 0 |
| 4 | "abab" (match) | 3 | 0 | 0 |
Here is how some of the non-obvious entries come out:
delta[1]['a']:p[1]is'b', so rule 3 applies and givesdelta[pi[0]]['a'] = delta[0]['a'] = 1. After reading "aa", the only prefix that still matches is "a".delta[3]['a']:p[3]is'b', so rule 3 givesdelta[pi[2]]['a'] = delta[1]['a'] = 1. After "abaa", the longest matching prefix is again "a".delta[4]['a']: rule 3 givesdelta[pi[3]]['a'] = delta[2]['a'] = 3. After a full match "abab", reading'a'leaves "aba" matched. This is how the overlapping match at index 2 is found.
Tracing the text "abababca" through this table:
| i | char | state after | match? |
|---|---|---|---|
| 0 | a | 1 | |
| 1 | b | 2 | |
| 2 | a | 3 | |
| 3 | b | 4 | yes, start 0 |
| 4 | a | 3 | |
| 5 | b | 4 | yes, start 2 |
| 6 | c | 0 | |
| 7 | a | 1 |
The result is [0, 2], the same as kmp_search. Both methods visit the same sequence of states. The automaton just reaches each one in a single step.
Why the Automaton Is Correct
The invariant from the KMP correctness chapter carries over unchanged. After reading text[0..i], the state equals the length of the longest prefix of p that is a suffix of text[0..i]. Plain KMP restores this invariant by walking the border chain until it finds a border that can be extended by c. Rule 3 says that delta[q][c] gives the same result as delta[pi[q - 1]][c] when c cannot extend the current match. That is one step of the same walk, and by induction on q the row for pi[q - 1] already holds the result of the rest of the chain. So every table entry equals what plain KMP would compute, and the search reports exactly the same matches.
This automaton also has the fewest possible states for its job, which is recognizing texts that end with p. A DFA must at least tell apart the m + 1 possible amounts of partial progress, and the KMP automaton uses exactly that many states.
Costs and Trade-offs
| Property | KMP with prefix function | KMP automaton |
|---|---|---|
| Preprocessing time | O(m) | O(m · σ), where σ is the alphabet size |
| Preprocessing memory | O(m) integers | O((m + 1) · σ) entries |
| Total search time | O(n) amortized | O(n) |
| Work per text character | Varies, with several fallbacks possible | Exactly one lookup |
| Inner loop | `while` with fallbacks | Single table read |
| Large alphabets | No extra cost | Dense table becomes expensive |
The number of fallbacks KMP makes on a single character is bounded by roughly log base φ of m (φ is the golden ratio). Fibonacci strings come close to this worst case. That number is small, but it is not constant. The automaton gives a hard O(1) bound per character.
The cost is the σ factor. For DNA (σ = 4) or a binary protocol stream, a dense table indexed by small integers is cheap and fast. For bytes (σ = 256), a pattern of length 1,000 needs about 256,000 entries. That is often still fine. For full Unicode, a dense table is impractical. The dictionary version above avoids the problem by storing only characters that occur in the pattern.
You can shrink the table further. Store only transitions whose target is not 0, and let lookups default to 0. For a KMP automaton the number of such transitions grows only linearly in m, so a sparse representation uses close to O(m) memory. Each lookup then becomes a hash or small-list search instead of an array index.
Common Mistakes
- Missing state m. As noted above, overlapping matches need the full row for state
m. - Building rows out of order. Rule 3 reads row
pi[q - 1], so rows must be filled forq = 0, 1, 2, ...in increasing order. - Dense tables over the wrong alphabet. If you index an array by character code, every possible text character needs a column, or a lookup will fail. Map unknown characters to state 0 explicitly.
- Empty pattern. The automaton would have only the accepting state 0. Handle the empty pattern separately, as
kmp_searchdoes, instead of building a table.
Streaming Use
The search state is a single integer, so the automaton is easy to run over a stream that arrives in chunks. Keep q between chunks and keep a running position counter. Nothing from earlier chunks needs to be buffered.
class StreamMatcher:
def __init__(self, pattern):
self.m = len(pattern)
self.delta = build_kmp_automaton(pattern, set(pattern))
self.q = 0
self.pos = 0
def feed(self, chunk):
found = []
for c in chunk:
self.q = self.delta[self.q].get(c, 0)
if self.q == self.m:
found.append(self.pos - self.m + 1)
self.pos += 1
return found
sm = StreamMatcher("abab")
print(sm.feed("aba")) # []
print(sm.feed("babca")) # [0, 2]Matches that cross a chunk boundary are found automatically, because the state carries the partial match across the boundary.
Exercise
Build the full transition table of the KMP automaton for the pattern "aab" over the alphabet {a, b}. Then give the state sequence for the text "aaab" and say where the match starts.
Show answer
The prefix function of "aab" is [0, 1, 0]. Rows: state 0: a→1, b→0. State 1: a→2, b→0 (p[1] is 'a', so b uses delta[pi[0]=0][b] = 0). State 2: a→2 (p[2] is 'b', so a uses delta[pi[1]=1][a] = 2), b→3. State 3: a→delta[pi[2]=0][a] = 1, b→delta[0][b] = 0. For "aaab" the states are 1, 2, 2, 3. State 3 is reached at index 3, so the match starts at 3 - 3 + 1 = 1.
Exercise
A colleague's automaton sets every transition out of state m to 0, "because the match is finished." On which input does it give a wrong answer for the pattern "aa", and what is the correct answer?
Show answer
With the text "aaa", the correct matches are [0, 1]. The buggy automaton reaches state 2 at index 1 (match at 0), resets to 0, then reads 'a' to reach state 1 at index 2, and so misses the match at 1. The correct transition is delta[2]['a'] = delta[pi[1]]['a'] = delta[1]['a'] = 2, which reports the overlapping occurrence.
Exercise
You need to search for one fixed 40-character pattern in a live 10 Gbit/s byte stream, and each byte must be handled within a fixed time budget. Should you use plain KMP or the KMP automaton, and what memory does a dense table need?
Show answer
Use the automaton. It does exactly one lookup per byte, while plain KMP can take several fallback steps on a single byte. A dense table needs (40 + 1) × 256 = 10,496 entries, which fits easily in cache. A sparse table could use less memory, but it would make each lookup slower.