Rabin-Karp and Rolling Hashes
The naive matcher compares characters to rule out a shift. Rabin and Karp (1987) replaced that with comparing one number: a hash of the text window against the hash of the pattern. The trick that makes it fast is the rolling hash: the hash of the next window is computed from the previous one in constant time. Equal hashes do not prove a match, so the algorithm still checks the characters on a hit, but with a good modulus false alarms are rare, and the expected running time is . The same rolling hash powers plagiarism detection, the rsync file-synchronization tool and searches for many patterns at once.
Strings as numbers
Over the digits , a window of characters is an -digit decimal number. Let be the value of the pattern and the value of . Then occurs with shift exactly when . By Horner's rule costs arithmetic operations, and moving the window one step is
drop the leading digit, shift, append the new digit. For a general alphabet of size , replace 10 by (for example for bytes).
The values have digits, too large to compare in constant time for long patterns. So compute everything modulo a prime : then every value fits in a machine word, with precomputed,
Now proves the shift invalid, but does not prove it valid: it may be a spurious hit, and the characters must be compared.
RABIN-KARP(T, P, d, q)
1 n = len(T); m = len(P)
2 h = d^(m-1) mod q
3 p = 0; t = 0
4 for i = 0 to m - 1 // preprocessing: Theta(m)
5 p = (d * p + P[i]) mod q
6 t = (d * t + T[i]) mod q
7 for s = 0 to n - m
8 if p == t and P[0 .. m-1] == T[s .. s+m-1]
9 report s
10 if s < n - m
11 t = (d * (t - T[s] * h) + T[s + m]) mod qThe animation runs it on a digit string with , small enough that spurious hits happen.
The program prints the same window hashes as the animation and counts the character comparisons spent on hits.
def rabin_karp(T, P, d=10, q=11, verbose=False):
n, m = len(T), len(P)
val = (lambda c: int(c)) if d == 10 else ord
h = pow(d, m - 1, q)
p = t = 0
for i in range(m):
p = (d * p + val(P[i])) % q
t = (d * t + val(T[i])) % q
found, spurious, comparisons = [], 0, 0
for s in range(n - m + 1):
if t == p:
j = 0
while j < m and T[s + j] == P[j]:
j += 1
comparisons += min(j + 1, m)
if j == m:
found.append(s)
else:
spurious += 1
if verbose:
print(f" shift {s:2}: hash {t:2} = {p}, " + ("match" if j == m else "spurious hit"))
elif verbose:
print(f" shift {s:2}: hash {t:2}")
if s < n - m:
t = (d * (t - val(T[s]) * h) + val(T[s + m])) % q
return found, spurious, comparisons
print("pattern hash:", int("2639") % 11)
found, spurious, comps = rabin_karp("5172639187263915", "2639", verbose=True)
print("matches", found, "| spurious hits", spurious, "| character comparisons", comps)pattern hash: 10
shift 0: hash 2
shift 1: hash 10 = 10, spurious hit
shift 2: hash 3
shift 3: hash 10 = 10, match
shift 4: hash 0
shift 5: hash 2
shift 6: hash 2
shift 7: hash 2
shift 8: hash 3
shift 9: hash 3
shift 10: hash 10 = 10, match
shift 11: hash 0
shift 12: hash 10 = 10, spurious hit
matches [3, 10] | spurious hits 2 | character comparisons 10
Python's % always returns a value in , even for the negative intermediate ; in C or C++ the remainder of a negative number is negative, so the code adds before reducing (see the C++ version below).
How often are hits spurious?
With the window hash takes only 11 values, so about one shift in 11 collides with the pattern by accident. Choosing a large prime makes collisions rare. Heuristically, if the hashes behave like random values mod , the expected number of spurious hits is about , and the expected running time is
with the number of valid shifts. For and few matches this is . The worst case remains , for example when every shift is valid (, ), since then every hit must be checked.
The heuristic can be made rigorous by choosing the modulus at random among the primes up to a bound : a fixed spurious hit means that divides the nonzero difference , which has fewer than prime factors, so a random prime is rarely one of them. Alternatively, fix a large prime and choose the base at random modulo ; then two different windows collide with probability at most , because their difference is a nonzero polynomial of degree below in .
import random
def rk_stats(T, P, q, d=256):
n, m = len(T), len(P)
h = pow(d, m - 1, q)
p = t = 0
for i in range(m):
p = (d * p + ord(P[i])) % q
t = (d * t + ord(T[i])) % q
hits = valid = 0
for s in range(n - m + 1):
if t == p:
hits += 1
valid += T[s:s + m] == P
if s < n - m:
t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q
return hits - valid, valid
rng = random.Random(8)
T = "".join(rng.choice("abcd") for _ in range(50000))
P = T[31337:31337 + 10]
print("text 50000 random letters from abcd, pattern of length 10 taken from it")
for q in [7, 13, 101, 1009, 65521, 2**31 - 1]:
spurious, valid = rk_stats(T, P, q)
print(f"q = {q:10}: spurious hits {spurious:5} (expected about {(len(T) - 9) / q:8.1f}), valid shifts {valid}")text 50000 random letters from abcd, pattern of length 10 taken from it
q = 7: spurious hits 7199 (expected about 7141.6), valid shifts 1
q = 13: spurious hits 3935 (expected about 3845.5), valid shifts 1
q = 101: spurious hits 513 (expected about 495.0), valid shifts 1
q = 1009: spurious hits 49 (expected about 49.5), valid shifts 1
q = 65521: spurious hits 1 (expected about 0.8), valid shifts 1
q = 2147483647: spurious hits 5 (expected about 0.0), valid shifts 1
Up to the counts follow the estimate . The last line is a warning: the Mersenne prime should give no spurious hits at all, yet it gives five. The reason is the base : since , reducing mod just folds the 80-bit window value into 31-bit groups and adds them, so different windows collide far more often than random values would. Hash quality depends on the pair , which is one more reason to pick the base at random.
Many patterns at once
Rabin-Karp extends naturally to searching for patterns of the same length: put the pattern hashes in a hash set and look up each window hash, for expected time. Two-dimensional matching (finding a small image in a large one) uses rolling hashes along rows and then along columns. For many patterns of different lengths, the Aho-Corasick automaton, a generalization of the next lesson's matcher, is the standard tool.
In C++
Rabin-Karp in C++ on bytes () with the prime . Products stay below because every value is reduced mod before multiplying.
#include <cstdio>
#include <string>
#include <vector>
std::vector<int> rabin_karp(const std::string& T, const std::string& P, int& spurious) {
const long long d = 256, q = 1000000007;
int n = int(T.size()), m = int(P.size());
std::vector<int> found;
spurious = 0;
if (m > n) return found;
long long h = 1, p = 0, t = 0;
for (int i = 0; i < m - 1; i++) h = h * d % q;
for (int i = 0; i < m; i++) {
p = (d * p + (unsigned char)P[i]) % q;
t = (d * t + (unsigned char)T[i]) % q;
}
for (int s = 0; s + m <= n; s++) {
if (t == p) {
if (T.compare(s, m, P) == 0) found.push_back(s); else spurious++;
}
if (s + m < n) {
t = (t - (unsigned char)T[s] * h % q + q) % q; // keep it non-negative
t = (t * d + (unsigned char)T[s + m]) % q;
}
}
return found;
}
int main() {
std::string T = "the cat sat on the mat; the cat ran", P = "the cat";
int spurious;
auto found = rabin_karp(T, P, spurious);
std::printf("\"%s\" found at:", P.c_str());
for (int s : found) std::printf(" %d", s);
std::printf(" (spurious hits: %d)\n", spurious);
found = rabin_karp("5172639187263915", "2639", spurious);
std::printf("\"2639\" found at:");
for (int s : found) std::printf(" %d", s);
std::printf(" (spurious hits: %d)\n", spurious);
}"the cat" found at: 0 24 (spurious hits: 0)
"2639" found at: 3 10 (spurious hits: 0)
With a modulus of a billion, the two spurious hits that produced disappear.
Test yourself
With and , the window "314" has hash . What is the hash of the next window "141" (the next text digit is 1)?
What is a spurious hit?
- A match missed by the algorithm
- A shift where the window hash equals the pattern hash but the strings differ
- A hash value larger than
- A match at shift 0
What is the worst-case running time of Rabin-Karp?
Why does the rolling update take constant time?
- Because the hash ignores most characters
- Because the new hash follows from the old one by removing the leading character's contribution, multiplying by and adding the new character, all mod
- Because is prime
- Because the pattern is short