Sub topic 11
Faster matching with KMP and Rabin-Karp
This chapter assumes you know the naive substring search from the previous chapter, can read Python, and understand Big-O notation. It also assumes you know what a hash function is: a function that maps data to a fixed-size number.
Where naive search wastes work
Naive search tries every starting position in the text. At each position it compares characters until one differs, then moves the start forward by one. It forgets everything it learned. In the worst case it costs O(n*m), where n is the text length and m is the pattern length.
Take the text abababaca and the pattern ababaca. At position 0, the search matches ababa, then fails on the sixth character. Naive search restarts at position 1. But the matched characters already tell us what the text holds there, so restarting at position 1 is wasted work. Two algorithms avoid this waste in different ways.
- KMP (Knuth-Morris-Pratt) never moves backward in the text. It uses a table built from the pattern to decide how much of the current match to keep.
- Rabin-Karp compares numeric fingerprints (hashes) of windows of text, and only compares characters when the fingerprints agree.
KMP: reuse what you already matched
KMP precomputes the prefix function of the pattern. For each position i, pi[i] is the length of the longest proper prefix of pattern[:i+1] that is also a suffix of it. A proper prefix is any prefix shorter than the whole string.
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
print(prefix_function("ababaca")) # [0, 0, 1, 2, 3, 0, 1]The value 3 at index 4 means that after matching ababa, the last three characters aba are also the first three characters of the pattern. If the next text character fails to extend the match, we do not need to start over. We fall back to a match length of 3 and try again from there.
def kmp_search(text, pattern):
if not pattern:
return 0
pi = prefix_function(pattern)
k = 0 # number of pattern characters currently matched
for i, ch in enumerate(text):
while k > 0 and ch != pattern[k]:
k = pi[k - 1]
if ch == pattern[k]:
k += 1
if k == len(pattern):
return i - k + 1
return -1
print(kmp_search("abababaca", "ababaca")) # 2
print(kmp_search("abababaca", "xyz")) # -1The text index i only increases. The variable k can drop, but it can only drop as far as it has previously risen. So the total work in the search loop is O(n), and building the table is O(m). KMP runs in O(n + m) in the worst case, and it needs O(m) extra memory for the table.
Rabin-Karp: compare fingerprints first
Rabin-Karp treats each window of m characters as a number and computes it with a rolling hash. When the window slides one position right, the new hash comes from the old one in O(1). You subtract the contribution of the outgoing character, shift, and add the incoming character.
def rabin_karp(text, pattern, base=256, mod=1_000_000_007):
n, m = len(text), len(pattern)
if m == 0:
return 0
if m > n:
return -1
high = pow(base, m - 1, mod) # weight of the leading character
hp = ht = 0
for i in range(m):
hp = (hp * base + ord(pattern[i])) % mod
ht = (ht * base + ord(text[i])) % mod
for i in range(n - m + 1):
if hp == ht and text[i:i + m] == pattern:
return i
if i < n - m:
ht = ((ht - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return -1
print(rabin_karp("abababaca", "ababaca")) # 2
print(rabin_karp("abababaca", "xyz")) # -1Different windows can share a hash value (a collision), so equal hashes only suggest a match. The code confirms with a real string comparison. With a good modulus, collisions are rare and the expected time is O(n + m). If the hash is weak, or an adversary picks the input, many windows can collide and the worst case returns to O(n*m).
Choosing between them
| Property | Naive | KMP | Rabin-Karp |
|---|---|---|---|
| Worst-case time | O(n*m) | O(n + m) | O(n*m) |
| Typical time | Near O(n) | O(n + m) | O(n + m) |
| Extra memory | O(1) | O(m) | O(1) |
| Handles many patterns | No | One at a time | Yes, by storing hashes in a set |
KMP gives a guarantee. Rabin-Karp is simple and extends well to searching for many patterns of the same length at once, which is why it is used in plagiarism detection.
Exercise
Compute the prefix function for the pattern "aabaaab". Then say what KMP does when it has matched "aabaa" (5 characters) and the next text character does not match.
Show answer
The prefix function is [0, 1, 0, 1, 2, 2, 3]. After matching "aabaa", k is 5, and pi[4] = 2. KMP sets k to 2, because the last two matched characters "aa" are also the pattern's first two characters. It then compares the mismatched text character against pattern[2] and does not move backward in the text.