Sub topic 6
Collisions and Why Every Match Must Be Verified
This chapter assumes you can compute a polynomial hash under a modulus and that you know the rolling update and the basic Rabin-Karp loop from the previous chapters. Here we look at the line p_hash == t_hash and text[i:i + m] == pattern and explain why the second half of that condition is required.
What a collision is
A hash function maps a huge set of strings onto a small set of values. With modulus p, there are only p possible hash values, but there are 26^m lowercase strings of length m. Once 26^m is larger than p, the pigeonhole principle says some different strings must share a hash. Two distinct strings with the same hash are a collision.
Equal hashes therefore tell you only that the strings might be equal. Unequal hashes are proof that the strings differ, because equal strings always produce equal hashes. Rabin-Karp relies on this one-sided guarantee:
| Hash comparison | What it proves |
|---|---|
| `h(a) != h(b)` | `a != b`, guaranteed |
| `h(a) == h(b)` | `a` and `b` are probably equal, so you must check |
A concrete collision
A small modulus makes collisions easy to see. With base 256 and modulus 101, 256 ≡ 54 (mod 101), so a two-character string hashes to (54·c1 + c2) mod 101. The strings "ah" and "ca" both hash to 90:
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
print(poly_hash("ah", mod=101), poly_hash("ca", mod=101)) # 90 90Now compare a search that trusts the hash with one that verifies each hash match:
def search(text, pattern, verify, base=256, mod=101):
n, m = len(text), len(pattern)
if m == 0 or m > n:
return []
high = pow(base, m - 1, mod)
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
hits = []
for i in range(n - m + 1):
if p_hash == t_hash and (not verify or text[i:i + m] == pattern):
hits.append(i)
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return hits
print(search("cab ah", "ah", verify=False)) # [0, 4] <- index 0 is wrong
print(search("cab ah", "ah", verify=True)) # [4]The unverified version reports "ca" at index 0 as a match. That wrong answer is a spurious hit. The direct comparison costs O(m), but it runs only when the hashes agree, and it removes every false positive.
How likely are collisions with a large prime?
If the hash values of different windows behave roughly at random, any one window collides with the pattern with probability about 1/p. Over n - m + 1 windows, the expected number of spurious hits is about (n - m + 1)/p. With p = 1_000_000_007 and a one-million-character text, that comes to roughly 0.001 per search.
That number is small, and that is exactly why skipping verification is tempting. The estimate still has limits:
- It is an average. A program that runs millions of searches will eventually see a collision.
- It assumes the input does not depend on your parameters. A fixed base and modulus can be attacked with inputs built to collide. Later chapters cover this.
- A wrong match is a correctness bug. A slow verification is only a performance cost.
Exercise
Using base 256 and modulus 101, explain why "ah" and "ca" collide without running code. Then say whether "ca" and "ah" would still collide with modulus 1000000_007.
Show answer
256 mod 101 = 54, so the hash is (54·c1 + c2) mod 101. Moving c1 up by 2 adds 108 ≡ 7, which is cancelled by moving c2 down by 7: 'a'→'c' (+2) and 'h'→'a' (−7). Both give 90. With modulus 1000000_007 the raw values 97·256+104 = 24936 and 99·256+97 = 25441 are both below the modulus and differ, so they do not collide.
Exercise
A search reports a hash match at 50 windows, but only 3 are true matches. With pattern length m, how much extra work did the spurious hits cost, and do they change the output of a verified search?
Show answer
The 47 spurious hits each cost up to O(m) character comparisons, so about 47·m extra work. They do not change the output, because verification rejects all of them.