Sub topic 13
KMP Compared with Other Matching Algorithms
This chapter assumes you know the prefix function, KMP search, and the O(n + m) proof from earlier chapters. It also assumes you are comfortable with Big-O notation and with hashing at a basic level. Here n is the text length and m is the pattern length.
KMP is one of several classic exact-matching algorithms. Each one makes a different trade-off between worst-case guarantees, typical speed, memory, and how easy it is to extend. Knowing those trade-offs tells you when KMP is the right tool and when another algorithm is better.
The Main Alternatives
Z-algorithm
The Z-function of a string s stores, for each position i, the length of the longest substring starting at i that is also a prefix of s. If you apply it to pattern + sep + text, every position where the value equals m marks a match. This is the same idea as the concatenation trick from the prefix-function chapter. The Z-algorithm also runs in O(n + m) time. Many people find it easier to reason about, because each value describes a match that starts at a position instead of one that ends there.
def z_function(s):
n = len(s)
z = [0] * n
l = r = 0
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l])
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i +
def z_search(text, pattern, sep="\0"):
# Assumes a non-empty pattern and a separator found in neither string.
m = len(pattern)
z = z_function(pattern + sep + text)
return [i - m - 1 for i in range(m + 1, len(z)) if z[i] >= m]
print(z_ab")) # [0, 2]The Z-algorithm has a practical drawback. In this form it needs the whole text in memory. KMP needs only the pattern's prefix function and the current state k, so it can process a stream one character at a time.
Boyer-Moore
Boyer-Moore compares the pattern from right to left. On a mismatch, it uses the bad-character rule and the good-suffix rule to shift the pattern, often by many positions at once. On natural-language text with a large alphabet, it usually skips most of the text and runs in sublinear time, roughly O(n / m). Simplified variants such as Boyer-Moore-Horspool have a worst case of O(n · m). The full algorithm can be made linear in the worst case, but it is harder to implement correctly. Fast library search routines, including GNU grep, are based on Boyer-Moore ideas.
Rabin-Karp
Rabin-Karp compares a rolling hash of each length-m window of the text with the hash of the pattern. It checks characters only when the hashes are equal. Its expected time is O(n + m), but hash collisions can push the worst case to O(n · m). Its strength is searching for many patterns of the same length at once: put all the pattern hashes in a set and check each window against it. It also extends naturally to two-dimensional matching.
Side-by-Side Comparison
| Algorithm | Preprocessing | Search (worst) | Search (typical) | Streams text? | Best fit |
|---|---|---|---|---|---|
| Naive | none | O(n · m) | near O(n) on random text | yes, with a buffer of size m | short patterns, quick code |
| KMP | O(m) | O(n) | O(n) | yes | guaranteed linear time, streaming, small alphabets |
| Z-algorithm | O(n + m) combined | O(n + m) | O(n + m) | no | offline matching, other string problems |
| Boyer-Moore | O(m + σ) | O(n · m) simple, O(n) full | sublinear | needs lookahead | long patterns, large alphabets |
| Rabin-Karp | O(m) | O(n · m) | O(n + m) expected | yes | many patterns, 2D matching |
In the table, σ is the alphabet size.
Choosing an Algorithm
Aho-Corasick is the multi-pattern generalization of the KMP automaton. It builds failure links over a trie of all the patterns.
Exercise
You must scan a network packet stream for one fixed 12-byte signature. Bytes arrive one at a time, you cannot buffer the stream, and the traffic may be adversarial. Which algorithm fits best, and why not Boyer-Moore or Rabin-Karp?
Show answer
KMP. It processes each byte once, keeps only the state k and the O(m) prefix function, and guarantees O(n) time on every input. Boyer-Moore needs to look ahead m bytes and compares from right to left, which conflicts with strict byte-at-a-time streaming, and its simple variants can degrade to quadratic time. Rabin-Karp can stream, but crafted hash collisions can push it to its O(n · m) worst case.
Exercise
Both KMP and the Z-algorithm run in O(n + m). Name one practical reason to prefer the Z-algorithm.
Show answer
Its values describe matches that start at each position, which makes many offline string problems easier to code and check, such as counting how often each prefix occurs. When the whole text is already in memory, streaming does not matter.