Sub topic 10
Double Hashing to Cut Collision Probability
This chapter assumes you have read the earlier chapters. You should be able to compute a polynomial hash modulo a prime, roll it across a window in O(1), and explain why Rabin-Karp verifies every hash match. You should also be comfortable with the birthday problem at the level of "n random values in a range of size p start repeating once n is around √p."
A single modulus near 10⁹ works well for one pattern against one text. It becomes a problem when your program compares a very large number of hashes, or when it trusts hash equality without checking the strings. Double hashing computes two independent hashes for each string and treats two strings as equal only when both hashes agree. The modulus space grows from about 10⁹ to about 10¹⁸ for roughly twice the arithmetic.
Where a Single Hash Runs Out
The per-comparison bound
Take two distinct strings s and t of length m. Their hash difference is a polynomial in the base b:
H(s) − H(t) = Σ (s[i] − t[i]) · b^(m−1−i) (mod p)
This polynomial is nonzero with degree at most m − 1. Over the field of integers mod a prime p it has at most m − 1 roots. If b is chosen uniformly at random from [0, p), then:
P(collision) ≤ (m − 1) / p
This is a worst-case guarantee that holds for any pair of inputs, including adversarial ones, as long as the base is random and secret. For m = 10⁵ and p ≈ 10⁹ the bound is 10⁻⁴ per comparison. Typical inputs do much better, close to 1/p. When you need a guarantee rather than a typical case, use the bound.
The birthday effect
Rabin-Karp compares each window against one pattern hash, which is about n comparisons. Many hashing applications instead put n hashes into a set and ask whether any two are equal. Longest repeated substring, which comes later in the tutorial, works this way. A set of n hashes contains n(n − 1)/2 pairs, so the expected number of false collisions is about n²/(2p).
| Hashes in the set (n) | Pairs | Expected false collisions, p ≈ 10⁹ | Expected, two moduli ≈ 10⁹ each | Expected, p = 2⁶¹ − 1 |
|---|---|---|---|---|
| 10⁴ | 5 × 10⁷ | 0.05 | 5 × 10⁻¹¹ | 2 × 10⁻¹¹ |
| 10⁵ | 5 × 10⁹ | 5 | 5 × 10⁻⁹ | 2 × 10⁻⁹ |
| 10⁶ | 5 × 10¹¹ | 500 | 5 × 10⁻⁷ | 2 × 10⁻⁷ |
These figures use the typical-case 1/p estimate. With a million substrings and one 10⁹ modulus, collisions are a near certainty. If the code doesn't verify, it will report wrong answers.
Seeing a collision happen
A small modulus makes the effect easy to see. The script below hashes random 8-letter strings mod 10007 until two different strings share a hash. By the birthday estimate this takes about √(π · 10007 / 2) ≈ 125 tries. The script then hashes the same two strings with a second, independent base and modulus.
import random
import string
def h(s, base, mod):
v = 0
for ch in s:
v = (v * base + ord(ch)) % mod
return v
def find_collision(base, mod, length=8, seed=0):
rng = random.Random(seed)
seen = {}
tries = 0
while True:
tries += 1
s = "".join(rng.choice(string.ascii_lowercase) for _ in range(length))
v = h(s, base, mod)
if v in seen and seen[v] != s:
return seen[v], s, tries
seen[v] = s
a, b, tries = find_collision(base=131, mod=10007)
print(a, b, "found after", tries, "strings")
print("hash 1 equal:", h(a, 131, 10007) == h(b, 131, 10007)) # True by construction
print("hash 2 equal:", h(a, 137, 10009) == h(b, 137, 10009)) # False except with probability about 1/10009The first hash says the strings are equal. The second hash almost always disagrees. A false match now requires both hashes to collide at once.
How Double Hashing Works
Choose two (base, modulus) pairs, (b₁, p₁) and (b₂, p₂). Maintain both hashes for every string or window. Treat the pair (H₁, H₂) as the fingerprint. If the bases are chosen independently and at random, the two collision events are independent, and the bounds multiply:
P(both collide) ≤ (m − 1)/p₁ · (m − 1)/p₂
With p₁ = 10⁹ + 7, p₂ = 998244353 and m = 10⁵, the worst-case bound falls from 10⁻⁴ to about 10⁻⁸ per comparison. The typical-case figure falls to about 10⁻¹⁸.
Rabin-Karp with two hashes
The rolling update is the same formula as before, applied once per modulus. Each modulus gets its own leading-character weight high.
import random
MOD1 = 1_000_000_007
MOD2 = 998_244_353
def rabin_karp_double(text, pattern, verify=True, seed=None):
rng = random.Random(seed)
b1 = rng.randrange(256, MOD1 - 1)
b2 = rng.randrange(256, MOD2 - 1)
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if m > n:
return []
high1 = pow(b1, m - 1, MOD1)
high2 = pow(b2, m - 1, MOD2)
p1 = p2 = t1 = t2 = 0
for i in range(m):
p1 = (p1 * b1 + ord(pattern[i])) % MOD1
p2 = (p2 * b2 + ord(pattern[i])) % MOD2
t1 = (t1 * b1 + ord(text[i])) % MOD1
t2 = (t2 * b2 + ord(text[i])) % MOD2
matches = []
for i in range(n - m + 1):
if t1 == p1 and t2 == p2:
if not verify or text[i:i + m] == pattern:
matches.append(i)
if i < n - m:
out, inc = ord(text[i]), ord(text[i + m])
t1 = ((t1 - out * high1) * b1 + inc) % MOD1
t2 = ((t2 - out * high2) * b2 + inc) % MOD2
return matches
print(rabin_karp_double("abracadabra", "abra", seed=1)) # [0, 7]
print(rabin_karp_double("aaaaa", "aa", verify=False)) # [0, 1, 2, 3]Python's % always returns a non-negative result, so the subtraction inside the update is safe here. The Java and C++ chapter showed how to add the modulus back before reducing. Do that for each of the two moduli.
Packing the pair into one key
A tuple (t1, t2) works as a dictionary or set key in Python. In Java or C++, a single 64-bit integer is faster to store and compare. Both hashes are below 2³⁰, so the following fits in a signed 64-bit long without overflow:
def pack(h1, h2, mod2=MOD2):
return h1 * mod2 + h2 # < MOD1 * MOD2 ≈ 1e18 < 2**63 ≈ 9.2e18The map from (h1, h2) to the packed key is one-to-one because h2 < mod2. Packing therefore loses no information.
Variants and Their Trade-offs
| Approach | Typical collision rate | Cost | Notes |
|---|---|---|---|
| One modulus ≈ 10⁹ | ~10⁻⁹ | 1× | Fine for a single pattern with verification |
| Two moduli ≈ 10⁹, random bases | ~10⁻¹⁸ | about 2× | Portable; every product fits in 64 bits |
| One modulus 2⁶¹ − 1, random base | ~4 × 10⁻¹⁹ | about 1× in Python, more in C++/Java | Needs a 128-bit multiply or a Mersenne reduction trick in fixed-width languages |
| Arithmetic mod 2⁶⁴ (natural overflow) | Unbounded on crafted input | Fastest | The modulus is not prime, and known strings defeat it for any base |
Some details matter in practice:
- Use the same base with different moduli. By the Chinese Remainder Theorem, hashing with base b modulo p₁ and p₂ equals hashing modulo p₁p₂ with that same base. The result is still strong if b is random. Independent bases are a little cleaner to analyze and cost nothing extra.
- Using the same modulus twice with different bases also works, since collisions under two independent random bases are independent events.
- Do not repeat the same pair. Two copies of (b, p) give two identical hashes and no extra protection. This bug is easy to introduce with copy-paste, so check it in code review.
- Fixed, public bases are a weak point. Two moduli with hard-coded bases are harder to break than one, but a determined adversary can still construct colliding inputs. Randomizing the bases at startup is what supports the probability bounds above. A later chapter covers attacks on hashes.
- Cost. Each window step does about twice the multiplications and reductions. In Python the overhead of the interpreter loop dominates, so the slowdown is often well under 2×. In C++ the added cost of the second hash is close to linear.
Exercises
Exercise
A program stores the hashes of all 200,000 substrings of length k in a set and reports "repeat found" whenever an insertion hits an existing hash, without verifying. Estimate the expected number of false reports per run with one modulus near 10⁹, and again with two independent moduli near 10⁹.
Show answer
There are about n²/2 = (2 × 10⁵)² / 2 = 2 × 10¹⁰ pairs. With one modulus the estimate is 2 × 10¹⁰ / 10⁹ = 20 false collisions per run, so false reports are effectively guaranteed. With two moduli the estimate is 2 × 10¹⁰ / 10¹⁸ = 2 × 10⁻⁸, which is negligible.
Exercise
A colleague's double-hash code uses (base=131, mod=1000000_007) for both hashes, then packs them as h1 * 998244353 + h2. What is wrong, and how do you fix it?
Show answer
Both hashes come from the same base and modulus, so h1 always equals h2. The second hash adds no information, and the collision probability is the same as a single hash. The packing step does not help either. Fix it by using a different modulus for the second hash (for example 998244353, which also matches the packing multiplier) and by drawing both bases at random at startup.
Exercise
Change rabinkarpdouble so that when verify=True it counts how many window positions had matching hash pairs but different strings. Run it on random text of length 10⁶ over the alphabet "ab" with a random pattern of length 20. What count do you expect, and why?
Show answer
Add a counter that is incremented when t1 == p1 and t2 == p2 but text[i:i+m] != pattern, and return it along with the matches. Expect 0. There are about 10⁶ comparisons, each with a typical false-collision chance near 10⁻¹⁸, which gives an expected count near 10⁻¹². Even the worst-case bound of (19/10⁹)² per comparison gives an expected count far below 1.