Sub topic 3
Why KMP Never Misses a Match
This chapter assumes you know the prefix function pi and the kmp_search loop from the previous chapters. It also assumes basic Big-O notation.
The Matching Invariant
After KMP reads text[i], the variable k holds the length of the longest prefix of the pattern that is also a suffix of text[0..i].
The fallback loop keeps this true. Every candidate length shorter than k must be a border of pattern[0..k-1]. The chain k, pi[k-1], pi[pi[k-1]-1], ... lists exactly those borders, from longest to shortest. KMP tries each one in order and keeps the first that the next character extends. It never skips a valid shorter prefix, so every position where k reaches m is a real match, and no match goes unreported.
Proving Linear Running Time
The text loop raises k by at most 1 for each character, so k goes up at most n times in total. Each step of the fallback loop lowers k by at least 1, and k never drops below 0. That means all the fallback steps together cannot outnumber the increases, so there are at most n of them. The search costs O(n). The same argument applied to the pattern gives O(m) for computing pi. The total is O(n + m).
Matching with a Single Prefix Function Pass
You can also join the pattern, a separator, and the text into one string and compute its prefix function. The separator must appear in neither the pattern nor the text, so no value of pi can exceed m. Every position where pi[i] == m is the end of a match.
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 find_with_concatenation(text, pattern, sep="\0"):
m = len(pattern)
s = pattern + sep + text
pi = prefix_function(s)
return [i - 2 * m for i in range(len(s)) if pi[i] == m]
print(find_with_concatenation("abababca", "abab")) # [0, 2]Finding Periods and Repetitions
The value n - pi[n-1] is the smallest period of a string s of length n. If that period divides n, then s is a whole number of copies of its first p characters.
def smallest_period(s):
if not s:
return 0
n = len(s)
p = n - prefix_function(s)[-1]
return p if n % p == 0 else n
print(smallest_period("abcabcabc")) # 3
print(smallest_period("abcab")) # 5The KMP Automaton
You can precompute delta[state][char] for every state and every character in the alphabet. The search then takes exactly one table lookup per text character and never runs a fallback loop. The table costs O(m·|Σ|) space, where |Σ| is the size of the alphabet. Use it for streaming input that needs a fixed cost per character, and only when the alphabet is small.
KMP Compared with Other Matching Algorithms
| Algorithm | Worst case | Best use |
|---|---|---|
| KMP | O(n + m) | Streams, guaranteed linear time |
| Z-algorithm | O(n + m) | Same jobs as KMP, and some find it simpler to reason about |
| Boyer-Moore | O(nm) in the basic version | Large alphabets, often sublinear in practice |
| Rabin-Karp | O(nm), O(n + m) expected | Many patterns of the same length |
Exercise
Why can the total number of fallback steps in kmp_search never exceed n?
Show answer
Each fallback lowers k by at least 1, k never goes below 0, and k rises at most once per text character. So the number of decreases is bounded by the n increases.
Exercise
What is the smallest period of "abaaba", and is the string an exact repetition?
Show answer
pi for "abaaba" ends at 3, so the period is 6 - 3 = 3. Since 3 divides 6, the string is "aba" repeated twice.