Sub topic 2
Putting It Together: The Rabin-Karp Algorithm
This chapter assumes you already know the polynomial hash and the rolling update from the previous chapter. It also assumes you are comfortable with Big-O notation and Python's % operator.
The Algorithm
Rabin-Karp hashes the pattern once. It then slides a window of the same length across the text and updates the window hash in O(1) at each step. When the two hashes are equal, it compares the actual characters before it reports a match.
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 leading character
p_hash = t_hash = 0
for i in range(m):
p_hash = (p_hash * base + ord(pattern[i])) % mod
t_hash = (t_hash * base + ord(text[i])) % mod
matches = []
for i in range(n - m + 1):
if p_hash == t_hash and text[i:i + m] == pattern:
matches.append(i)
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return matches
print(rabin_karp("abracadabra", "abra")) # [0, 7]Collisions: Always Verify
A hash maps strings into only mod possible values, so two different strings can share a hash. This is called a collision. If you report a match on hash equality alone, you will sometimes return false positives. The text[i:i + m] == pattern check costs O(m). It runs only when the hashes match, and it makes the output exactly correct.
Running Time
| Case | Cost | Why |
|---|---|---|
| Expected | O(n + m) | Hashing takes O(m), rolling takes O(n), and collisions are rare |
| With k true matches | O(n + m + km) | Each real match is verified |
| Worst case | O(nm) | Every window matches or collides |
Text "aaaa…" with pattern "aa…a" hits the worst case even when no collision happens, because every window is a real match.
Choosing the Base and Modulus
- Modulus: use a large prime such as
1_000_000_007. A larger modulus lowers the collision rate. - Base: use a value at least as large as the alphabet size, such as 256 for bytes.
- Randomize: if you pick the base at random from
[256, mod - 1], two fixed, distinct strings of length m collide with probability at most about m / mod. A fixed base and modulus can be attacked with inputs built to collide. A base chosen at random at runtime cannot be targeted in advance.
Exercise
The pattern is "ab" and the text is "abab". How many times does the character check run, assuming no collisions? What is the result?
Show answer
The window hashes are "ab", "ba", "ab". Only windows 0 and 2 match the pattern hash, so the character check runs twice. Both checks succeed, and the result is [0, 2].
Exercise
Why is it unsafe to skip verification when the modulus is huge, for example 2^61 - 1?
Show answer
A huge modulus only makes collisions rarer. It cannot remove them, because there are more possible strings than hash values. Without verification, any collision returns a wrong answer.