Sub topic 10
Double Hashing to Cut Collision Probability
This chapter assumes you already have a working Rabin-Karp search with one modulus, and that you know why a hash match has to be verified. It also assumes you understand how the choice of base and modulus affects collisions. Double hashing keeps two independent hashes of every window. A window becomes a candidate only when both hashes agree with the pattern's.
Why One Modulus Can Be Too Few
Suppose the base is chosen at random and the modulus is a prime p. Two different strings of length m then collide with probability at most about (m − 1)/p. When p is near 10^9, a single comparison almost never gives a false match. The risk grows when you make many comparisons. Storing one million substring hashes in a set creates about 5 × 10^11 pairs. By the birthday bound, at least one collision among them is close to certain. This is the usual workload in multi-pattern search and in the longest-repeated-substring technique.
Two hashes with independent moduli p1 and p2 make the hash pair behave like a single hash modulo p1 · p2, which is about 10^18. The per-pair collision probability falls to about 1/(p1 · p2). With that value, one million stored hashes almost certainly contain no collision.
| Setup | Effective range | Approx. per-pair collision | Safe for ~10^6 stored hashes? |
|---|---|---|---|
| One mod, p ≈ 10^9 | 10^9 | 10^-9 | No |
| Two mods, p1, p2 ≈ 10^9 | 10^18 | 10^-18 | Yes |
| One 61-bit Mersenne mod | 2.3 × 10^18 | 4 × 10^-19 | Yes |
How It Fits the Rolling Update
Each modulus gets its own hash value and its own leading-character weight, base^(m−1) mod p. The rolling update from earlier chapters runs once per modulus. The two values are then compared together as a pair.
def rabin_karp_double(text, pattern, base=256, mods=(1_000_000_007, 998_244_353)):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
highs = [pow(base, m - 1, q) for q in mods]
p_hash = [0, 0]
t_hash = [0, 0]
for i in range(m):
for k, q in enumerate(mods):
p_hash[k] = (p_hash[k] * base + ord(pattern[i])) % q
t_hash[k] = (t_hash[k] * base + ord(text[i])) % q
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:
for k, q in enumerate(mods):
t_hash[k] = ((t_hash[k] - ord(text[i]) * highs[k]) * base
+ ord(text[i + m])) % q
return matches
print(rabin_karp_double("abracadabra", "abra")) # [0, 7]In plain search, keep the direct comparison anyway. It costs O(m) only when a candidate appears, and it guarantees correct output. In set-based uses, such as checking whether any substring of length L repeats, you often skip verification and trust the pair. That is the case where the second hash matters most.
Common Errors
- Reusing one
highvalue for both moduli. Each modulus needs its own base^(m−1) mod p. - Comparing only the first hash. Both components must match. In Python, comparing the two lists does this.
- Overflow in Java or C++. Each product must stay below 2^63. Two moduli near 10^9 are safe with
long. A product of two values near 2^61 is not safe, so it needs 128-bit multiplication. - Expecting a lower worst case. Double hashing reduces the chance of a collision. A crafted input with many true matches still forces O(nm) verification.
Double hashing roughly doubles the hashing work. A single 61-bit Mersenne modulus gives similar safety with one hash, but it needs careful multiplication in fixed-width languages.
Exercise
You store hashes of all 2 × 10^5 substrings of length L in a set to detect a repeat, and you skip verification. Estimate the expected number of colliding pairs with one modulus near 10^9 and with two independent moduli near 10^9.
Show answer
The number of pairs is about (2 × 10^5)^2 / 2 = 2 × 10^10. With one modulus, about 2 × 10^10 / 10^9 = 20 false collisions are expected, so the result is unreliable. With two moduli, about 2 × 10^10 / 10^18 = 2 × 10^-8 are expected, which is negligible.
Exercise
Why does double hashing not improve Rabin-Karp's worst-case running time on text "aaaa...a" with pattern "aa...a"?
Show answer
Every window is a true match, so every window needs O(m) verification no matter how many hashes you use. The total work stays O(nm).