Sub topic 13
KMP Compared with Other Matching Algorithms
This chapter assumes you have read the earlier chapters. You should know the prefix function, KMP search, and the amortized O(n + m) proof. You should also be comfortable with Big-O notation and with modular arithmetic at the level of "take the remainder after division." Throughout, n is the text length and m is the pattern length.
KMP is rarely the only option. Three other algorithms come up whenever exact string matching is discussed: the Z-algorithm, Boyer-Moore, and Rabin-Karp. Each one makes a different trade-off between worst-case guarantees, average speed, memory, and flexibility. This chapter explains how each one works, gives a runnable version of each, and ends with criteria for choosing between them.
The Z-Algorithm: KMP's Close Relative
How it works
The Z-array of a string s stores, at each position i, the length of the longest substring starting at i that is also a prefix of s. KMP's prefix function looks backward from each position and asks "which prefix ends here?" The Z-array looks forward and asks "which prefix starts here?"
To match, you build pattern + separator + text and compute its Z-array. Any position in the text part whose Z-value equals m is the start of an occurrence. This is the same concatenation trick from the earlier chapter, applied with the Z-array in place of the prefix function.
def z_function(s):
n = len(s)
z = [0] * n
l = r = 0 # [l, r) is the rightmost window known to match a prefix
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 + z[i]
if n:
z[0] = n
return z
def z_search(text, pattern, sep="\0"):
m = len(pattern)
if m == 0:
return list(range(len(text) + 1))
s = pattern + sep + text
z = z_function(s)
return [i - m - 1 for i in range(m + 1, len(s)) if z[i] >= m]
print(z_function("aabxaab")) , 0, 0, 3, 1, 0]
print(z_search("abababca", "abab")) # [0, 2]Trade-offs against
Both algorithms run in O(n + m) worst-case time, and each array can be converted into the other in linear time. So the real differences are practical:
- Streaming. KMP needs only the pattern's prefix function, which takes O(m) memory, and it reads the text one character at a time without going back. The concatenation version of the Z-algorithm needs the whole text in memory and allocates an O(n + m) array. You can write a streaming Z-based matcher, but that is no longer the textbook algorithm.
- Ease of reasoning. Many people find Z-values easier to picture, because "the prefix match starting here has length 5" is a concrete statement. Competitive programmers often choose Z for problems about prefixes that occur at given positions.
- Separator requirement. The concatenation approach breaks if the separator can appear in the input. KMP search over the text has no such requirement.
Boyer-Moore: Skipping Ahead
How it works
Boyer-Moore compares the pattern against the text from right to left. When a mismatch happens, it can often shift the pattern by many positions at once, sometimes by the full length m. It uses two rules:
- The bad-character rule looks at the text character that caused the mismatch and shifts so that the rightmost occurrence of that character in the pattern lines up with it. If the character does not occur in the pattern at all, the whole pattern moves past it.
- The good-suffix rule looks at the suffix that already matched and shifts to the next place where that suffix (or a border-like piece of it) appears in the pattern. Its preprocessing is close to the prefix function computed on the reversed pattern.
Boyer-Moore-Horspool is a simplified version that is widely used. It keeps only a bad-character table, indexed by the text character aligned with the last pattern position. It is short enough to show in full:
def horspool(text, pattern):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
# Distance from the last occurrence of c (excluding the final char) to the end.
shift = {c: m - 1 - i for i, c in enumerate(pattern[:-1])}
matches = []
i = 0
while i <= n - m:
if text[i:i + m] == pattern:
matches.append(i)
i += shift.get(text[i + m - 1], m)
return matches
print(horspool("abababca", "abab")) # [0, 2]
print(horspool("here is a simple example", "example")) # [17]Gotchas
- Average case is sublinear. On natural-language text with a long pattern, Boyer-Moore inspects only about n / m characters. KMP always inspects at least n characters. For long patterns over large alphabets, this makes Boyer-Moore faster in practice.
- Worst case depends on the variant. Horspool and the original Boyer-Moore take O(n · m) in the worst case when reporting all matches. For example, text
aaaa…aand patternaaa…aforce a full comparison at every single-step shift. Full Boyer-Moore with the Galil rule brings the worst case down to O(n + m). - Small alphabets hurt. On DNA, which has 4 letters, or on binary data, the bad-character rule seldom gives long shifts, and most of the advantage disappears.
- The text must allow random access. Boyer-Moore jumps ahead and reads characters out of order, so it does not fit a one-pass stream the way KMP does.
Rabin-Karp: Hashing Windows
How it works
Rabin-Karp computes a hash of the pattern and a rolling hash of every length-m window of the text. A rolling hash can be updated in O(1) time when the window slides one position. When the two hashes are equal, the algorithm compares the characters to confirm the match, because different strings can share a hash.
def rabin_karp(text, pattern, base=256, mod=1_000_000_007):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
high = pow(base, m - 1, mod) # weight of the leftmost character
ph = th = 0
for i in range(m):
ph = (ph * base + ord(pattern[i])) % mod
th = (th * base + ord(text[i])) % mod
matches = []
for i in range(n - m + 1):
if ph == th and text[i:i + m] == pattern:
matches.append(i)
if i < n - m:
th = ((th - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return matches
print(rabin_karp("abababca", "abab")) # [0, 2]Gotchas
- The guarantee is probabilistic. Expected time is O(n + m) when collisions are rare. An adversary who knows your base and modulus can build inputs that collide at every window, which pushes the cost to O(n · m). Choosing the base at random when the program starts defends against this.
- Skipping verification is risky. If you skip the character comparison to save time, the algorithm becomes a Monte Carlo algorithm: it is always fast but can occasionally report a false match. That trade is sometimes acceptable, for example in near-duplicate detection, but it must be a deliberate choice.
- Many patterns at once. Rabin-Karp is at its best with many patterns of the same length. Put all pattern hashes in a set, and every window then needs a single set lookup. This approach also extends to two-dimensional matching and to finding repeated substrings.
Side-by-Side Comparison
| Algorithm | Preprocessing | Search, worst case | Search, typical | Extra space | One-pass streaming | Best fit |
|---|---|---|---|---|---|---|
| Naive | none | O(n · m) | close to O(n) on random text | O(1) | needs a window buffer | tiny inputs, simplicity |
| KMP | O(m) | O(n + m) | O(n + m) | O(m) | yes | guaranteed linear time, streams, small alphabets |
| Z-algorithm | O(n + m) with concatenation | O(n + m) | O(n + m) | O(n + m) | not in its standard form | prefix-match questions, contests |
| Boyer-Moore (Galil) | O(m + σ) | O(n + m) | about O(n / m) | O(m + σ) | no | long patterns, large alphabets |
| Horspool | O(m + σ) | O(n · m) | about O(n / m) | O(σ) | no | simple fast search on ordinary text |
| Rabin-Karp | O(m) | O(n · m) | O(n + m) expected | O(1), or O(k) for k patterns | yes | many same-length patterns, 2D matching |
Here σ is the alphabet size. In Python, the dictionary in horspool only stores characters that appear in the pattern, so its size is at most m.
Choosing an Algorithm
Some practical points:
- Use the library first. Python's
str.findand C'smemmemare hand-tuned. CPython combines a Horspool-style search with the Crochemore-Perrin Two-Way algorithm for longer patterns, and glibc uses Two-Way. Two-Way guarantees linear time with O(1) extra space. Write your own matcher only when you need something the library does not provide, such as streaming input, all overlapping matches with a guaranteed bound, or reuse of the prefix function for another purpose. - KMP is the base of other algorithms. Aho-Corasick extends the failure links from a single pattern to a trie of many patterns. The KMP automaton from the previous chapter gives constant time per character, which matters in hardware and in regular-expression engines.
- Test against a reference. Whichever algorithm you implement, compare it with naive search on random inputs over a small alphabet. Inputs with many repeated letters are the ones that expose bugs in shifts and fallbacks.
import random
def naive_search(text, pattern):
n, m = len(text), len(pattern)
return [i for i in range(n - m + 1) if text[i:i + m] == pattern]
for _ in range(2000):
t = "".join(random.choice("ab") for _ in range(random.randint(0, 20)))
p = "".join(random.choice("ab") for _ in range(random.randint(1, 5)))
expected = naive_search(t, p)
assert z_search(t, p) == expected
assert horspool(t, p) == expected
assert rabin_karp(t, p) == expected
print("all algorithms agree")Run this block after the three earlier blocks in this chapter so that z_search, horspool, and rabin_karp are defined.
Exercise
You must scan a 50 GB network capture as it arrives, looking for one fixed 12-byte signature. An attacker can control the traffic. Which algorithm from this chapter fits best, and why do the others fall short?
Show answer
KMP. It reads each byte once and never moves backward, keeps only O(m) state, and guarantees O(n + m) time no matter what the input is. Boyer-Moore and Horspool need random access ahead of the current position, and Horspool can degrade to O(n · m) on crafted input. An attacker who can guess the hash parameters can force collisions in Rabin-Karp. The Z-algorithm with concatenation needs the whole text in memory.
Exercise
Give a text and pattern on which Horspool performs about n · m character comparisons, and explain why KMP does not suffer on the same input.
Show answer
Use text "a" n and pattern "a" m. Every window matches, so Horspool compares all m characters at each position. The last pattern character is 'a', whose shift is 1, so the window advances by one each time, for roughly (n - m + 1) · m comparisons. After each match, KMP falls back to k = pi[m - 1] = m - 1 and needs only one new comparison per text character, for O(n + m) in total.
Exercise
You need to find which of 10,000 banned 8-character codes appear anywhere in a long document. Compare running KMP once per code with using Rabin-Karp.
Show answer
Running KMP once per code costs about 10,000 · (n + 8) steps. Rabin-Karp hashes every 8-character window once and checks each hash against a set of the 10,000 pattern hashes, which costs O(n + total pattern length) expected time, plus a character comparison on each hash hit. For patterns of different lengths, Aho-Corasick gives a deterministic linear-time bound.