Sub topic 6
Collisions and Why Every Match Must Be Verified
This chapter assumes you have read the earlier chapters on polynomial hashing and the rolling update. You should be able to compute h(s) = (s[0]·b^(m-1) + ... + s[m-1]) mod p and slide it one character in O(1). You also need basic Python and the modulo operator.
The Rabin-Karp loop from the previous chapter contains the condition p_hash == t_hash and text[i:i + m] == pattern. This chapter explains why the second half of that condition is required, what goes wrong without it, and how to test that your verification step works.
What a Collision Is
A collision happens when two different strings get the same hash value. In Rabin-Karp, a collision between the pattern and a text window is called a spurious hit: the hashes match, but the strings do not.
Collisions cannot be avoided. With base 256, there are 256^m possible strings of length m, but only p possible hash values. Once 256^m > p, the pigeonhole principle says some pair of distinct strings must share a hash. For p = 1,000,000,007 that is already true at m = 4. No choice of modulus removes collisions. A larger modulus only makes them rarer.
A Collision You Can Check by Hand
Take a deliberately tiny modulus, p = 13, with base 256. Since 256 mod 13 = 9, the hash of a two-character string xy is (ord(x)·9 + ord(y)) mod 13.
| String | ord values | Computation mod 13 | Hash |
|---|---|---|---|
| `ab` | 97, 98 | 6·9 + 7 = 61 | 9 |
| `ao` | 97, 111 | 6·9 + 7 = 61 | 9 |
| `nb` | 110, 98 | 6·9 + 7 = 61 | 9 |
| `ba` | 98, 97 | 7·9 + 6 = 69 | 4 |
'b' (98) and 'o' (111) differ by exactly 13, so they are congruent mod 13 and contribute the same amount to the hash. The same holds for 'a' (97) and 'n' (110). Any two strings whose character codes differ by multiples of p at the same positions collide. With a real modulus the colliding strings are less obvious, but they exist for the same reason.
When Exactly Two Strings Collide
Let x and y be distinct strings of length m. Their hashes are equal exactly when
(x[0] - y[0])·b^(m-1) + (x[1] - y[1])·b^(m-2) + ... + (x[m-1] - y[m-1]) ≡ 0 (mod p)
The left side is a polynomial in b of degree at most m − 1, and it is not the zero polynomial because x ≠ y. When p is prime, a nonzero polynomial of degree d has at most d roots mod p. So if b is picked uniformly at random from {0, ..., p − 1}, then:
Pr[h(x) = h(y)] ≤ (m - 1) / p
This bound only holds when b is random and the strings are fixed before b is chosen. If b is fixed and public, someone can search for strings that make the polynomial vanish. The later chapters on parameter choice and anti-hash tests come back to this. For now, the bound tells you that collisions are rare for a large prime, but their probability is never zero.
Spurious Hits in Action
The search below takes a verify flag, so you can see both behaviors on the same input. It uses p = 13 on purpose so that a collision shows up.
def search(text, pattern, base=256, mod=13, verify=True):
n, m = len(text), len(pattern)
if m == 0 or m > n:
return [], 0
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, spurious = [], 0
for i in range(n - m + 1):
if p_hash == t_hash:
if not verify or text[i:i + m] == pattern:
hits.append(i)
else:
spurious += 1
if i < n - m:
t_hash = ((t_hash - ord(text[i]) * high) * base + ord(text[i + m])) % mod
return hits, spurious
print(search("abaoab", "ab", verify=False)) # ([0, 2, 4], 0)
print(search("abaoab", "ab")) # ([0, 4], 1)The windows are ab, ba, ao, oa, ab. Without verification, the window ao at index 2 is reported as a match. With verification, the direct comparison rejects it and the code counts one spurious hit.
False Positives Only, Never False Negatives
A correct hash function is deterministic: equal strings always produce equal hashes. So the hash filter can never reject a real match. The only error it can make is letting a non-match through. That asymmetry is why one check is enough. The hash comparison removes almost every window cheaply, and the character comparison removes the rare false positives that remain.
| Variant | Correctness | Running time | Algorithm class |
|---|---|---|---|
| Hash check + verification | Always correct | Varies with the number of hash hits | Las Vegas |
| Hash check only | Wrong with small probability | Always O(n + m) | Monte Carlo |
Some applications accept the Monte Carlo variant, for example approximate deduplication, where a rare false positive is cheap. For a function named find or search, return only verified matches.
What Verification Costs
Each verification compares up to m characters, so it costs O(m). Real matches always pay that cost, and that is unavoidable because you must report them. Spurious hits also pay it, and that cost is waste. With a well-chosen large prime, spurious hits are so rare that the total waste is negligible. The next chapter turns this into the expected O(n + m) bound and shows when it fails and drops to O(nm).
In Python, text[i:i + m] == pattern builds a new string before comparing. text.startswith(pattern, i) does the same check without copying, which helps when m is large:
text, pattern, i = "abracadabra", "abra", 7
print(text[i:i + len(pattern)] == pattern) # True, allocates a slice
print(text.startswith(pattern, i)) # True, no slice allocatedMeasuring the Spurious-Hit Rate
If window hashes behave roughly like uniform random values, each non-matching window has about a 1/p chance of a spurious hit. Over n − m + 1 windows, you should expect about (n − m + 1)/p of them.
import random
def count_spurious(text, pattern, mod):
_, spurious = search(text, pattern, mod=mod)
return spurious
random.seed(1)
text = "".join(random.choice("abcd") for _ in range(100_000))
pattern = "".join(random.choice("abcd") for _ in range(8))
for mod in (13, 1009, 1_000_000_007):
print(mod, count_spurious(text, pattern, mod))This reuses search from above. Expect thousands of spurious hits for p = 13, roughly a hundred for p = 1009, and almost certainly zero for p = 1,000,000,007. The exact counts depend on the seed. What matters is that the count shrinks in proportion to 1/p.
Stress-Testing the Verification Path
With a large modulus, the spurious-hit branch almost never runs, so an ordinary test can pass even if that branch is broken. To test it, set a tiny modulus to force frequent collisions, then compare the output against the naive algorithm:
import random
def naive(text, pattern):
m = len(pattern)
return [i for i in range(len(text) - m + 1) if text[i:i + m] == pattern]
random.seed(7)
for _ in range(2000):
text = "".join(random.choice("ab") for _ in range(random.randint(1, 30)))
pattern = "".join(random.choice("ab") for _ in range(random.randint(1, 5)))
hits, _ = search(text, pattern, mod=7)
assert hits == naive(text, pattern), (text, pattern)
print("all tests passed")If the test passes with mod = 7, then both the rolling update and the verification are working. If you run it with verify=False, it fails almost immediately. That failure shows the test can actually catch a missing verification step.
Exercises
Exercise
With base 256 and modulus 13, does the string "nn" collide with "aa"? Explain without computing the full hashes.
Show answer
Yes. ord('n') = 110 and ord('a') = 97 differ by 13, so they are congruent mod 13. Each position contributes the same amount to the hash mod 13, so h("nn") = h("aa"). Both equal (6·9 + 6) mod 13 = 60 mod 13 = 8.
Exercise
A Rabin-Karp implementation without verification misses an occurrence of the pattern that is really in the text. Can a hash collision explain this?
Show answer
No. Collisions only cause false positives, because equal strings always hash to equal values. A missed match points to a bug in the hash computation or the rolling update, such as using base^m instead of base^(m-1), skipping a modulo reduction, or getting a negative remainder.
Exercise
You search a text of 10^7 characters for a pattern of length 20 using a prime modulus p ≈ 10^9 and treat window hashes as uniform random. About how many spurious hits do you expect, and roughly how many character comparisons do they cost in total?
Show answer
About (10^7 − 19)/10^9 ≈ 0.01 spurious hits. Each one costs at most 20 comparisons, so the expected waste is about 0.2 character comparisons, which is negligible.
Exercise
Why does the stress test use mod=7 instead of the default 1,000,000,007?
Show answer
With a large modulus, spurious hits almost never occur on short random inputs, so the verification branch would go untested. A tiny modulus forces many collisions, so a missing or broken verification step produces wrong output that the comparison with the naive algorithm catches.