Sub topic 8
Choosing the Base and Modulus
This chapter assumes you already know the polynomial hash h = (h * base + ord(ch)) % mod, the rolling update, and why Rabin-Karp verifies every hash match. Here we look at the two numbers that hash depends on. The base and the modulus decide how often collisions happen, how fast the arithmetic runs, and whether someone who knows your code can force it into its slowest case.
What Each Parameter Controls
The hash of a string s of length m is:
H(s) = (s[0]·b^(m-1) + s[1]·b^(m-2) + ... + s[m-1]) mod p
Each parameter has its own job:
| Parameter | Role | What goes wrong if chosen badly |
|---|---|---|
| Base `b` | Gives each position its own weight, so order matters | Strings that differ only in order or in early characters hash the same |
| Modulus `p` | Caps the range of hash values and keeps numbers small | Too small: many collisions. Too large: intermediate products overflow |
| Randomness of `b` | Means no single input is bad for every run | A fixed `b` lets an attacker build colliding strings ahead of time |
Failure Modes of Bad Choices
The easiest way to see what the rules are for is to break them on purpose.
def poly_hash(s, base, mod):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
# Base 1: the hash is just the sum of character codes, so anagrams collide.
print(poly_hash("listen", 1, 1_000_000_007) == poly_hash("silent", 1, 1_000_000_007)) # True
# Base equals modulus: h * base % mod is always 0, so only the last character survives.
print(poly_hash("cat", 256, 256), poly_hash("hat", 256, 256)) # 116 116
# Base shares a factor with the modulus: 10^3 = 0 mod 1000, so only the last 3 chars matter.
print(poly_hash("xxabc", 10, 1000) == poly_hash("yyabc", 10, 1000)) # True
# A reasonable choice: large prime modulus, base unrelated to it.
print(poly_hash("listen", 911382323, 1_000_000_007) == poly_hash("silent", 911382323, 1_000_000_007)) # FalseThese examples point to three rules.
- The base must not be 0 or 1 modulo
p. With base 0 only the last character counts. With base 1 the hash is a plain sum. gcd(b, p)must be 1. Ifbandpshare a factor, high powers ofbcan become 0 modulop, and the hash forgets characters at the start of the window. The rolling update also breaks, because it relies on the weightb^(m-1)being meaningful.pshould be a prime larger than the alphabet. A prime modulus makes rule 2 automatic for any1 < b < p. A modulus larger than every character code means two different characters never look the same after reduction.
Why a Prime Modulus and a Random Base Work
The case for a large prime p and a random b rests on a short argument.
Take two different strings s and t of length m. Their hash difference is:
H(s) − H(t) = Σ (s[i] − t[i]) · b^(m-1-i) (mod p)
Read this as a polynomial in the variable b. Its coefficients are the character differences s[i] − t[i]. Because s ≠ t, at least one coefficient is nonzero. Because p is larger than the alphabet, that coefficient stays nonzero modulo p. So the polynomial is not identically zero, and its degree is at most m − 1.
When p is prime, the integers modulo p form a field. A nonzero polynomial of degree d over a field has at most d roots. A collision happens exactly when b is a root. If b is drawn uniformly from p possible values:
Pr[H(s) = H(t)] ≤ (m − 1) / p
This bound holds for every pair of distinct strings. The probability comes from your random choice of b, so it does not depend on the input. That is what randomization gets you. With a fixed b, the bound says nothing about a particular input, and someone who knows b can search for a pair of roots.
Apply this to Rabin-Karp. Each of the n − m + 1 windows is a chance for a false positive, so:
expected false positives ≤ n(m − 1) / p
Each false positive costs an O(m) verification. The extra expected work is therefore about n·m²/p, which is negligible as long as p is much larger than n·m.
Sizing the Modulus
Two separate pressures set the size of p.
The collision pressure grows with the number of comparisons. A Rabin-Karp scan makes about n window comparisons, each failing with probability about m/p. A different situation is storing k hashes in a set and asking whether any two collide, as the longest-repeated-substring chapter does. That case follows the birthday bound: about k² / (2p) expected colliding pairs. One million hashes under p ≈ 10⁹ gives about 500 expected collisions. Under p ≈ 2.3·10¹⁸ it gives about 2·10⁻⁷.
The overflow pressure caps p in fixed-width languages. The rolling step multiplies a value below p by b < p, so the product can approach p². For that product to fit in a signed 64-bit integer, p must stay below about 3·10⁹. That limit is why 10⁹ + 7 is so common. Larger moduli need 128-bit intermediate products. The overflow chapter covers the mechanics.
You can measure the birthday effect directly with a deliberately small modulus:
import random
from collections import Counter
def poly_hash(s, base, mod):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
def colliding_pairs(strings, base, mod):
counts = Counter(poly_hash(s, base, mod) for s in strings)
return sum(c * (c - 1) // 2 for c in counts.values())
random.seed(1)
mod = 10007
strings = set()
while len(strings) < 2000:
strings.add("".join(random.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(8)))
k = len(strings)
base = random.randrange(2, mod - 1)
print("observed:", colliding_pairs(strings, base, mod))
print("birthday estimate:", round(k * (k - 1) / (2 * mod))) # about 200The observed count lands close to 200. Raise mod to (1 << 61) - 1 and it drops to 0.
Common Concrete Choices
| Modulus `p` | Size | Multiplication needs | Typical use |
|---|---|---|---|
| `10⁹ + 7` or `998244353` | ~2³⁰ | 64-bit product | Single scans, small `k`; usually paired for double hashing |
| `2⁶¹ − 1` (Mersenne prime) | ~2⁶¹ | 128-bit product, fast reduction by shifts | Large hash sets, binary search over substrings |
| `2⁶⁴` (implicit unsigned overflow) | 2⁶⁴ | None, it's free | Avoid: not prime, and known inputs break it for any odd base |
The 2⁶⁴ row is a trap. Letting unsigned integers wrap around looks like a free modulus. It is not a field, so the root-counting argument does not apply. There is a known family of strings (built from the Thue–Morse sequence) that collide under 2⁶⁴ for every odd base. Randomizing the base does not help there. The anti-hash chapter builds that input.
Picking Parameters at Runtime
In practice, fix a large prime and draw the base fresh on each run:
import random
MOD = (1 << 61) - 1 # Mersenne prime, about 2.3e18
BASE = random.randrange(256, MOD - 1) # random, far from 0 and 1
def rabin_karp(text, pattern, base=BASE, mod=MOD):
n, m = len(text), len(pattern)
if m == 0:
return list(range(n + 1))
if 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
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]Python integers have arbitrary size, so 2⁶¹ − 1 costs nothing extra here. In C++ the product needs unsigned __int128. In Java it needs Math.multiplyHigh or a split multiplication.
Use random for contests and ordinary programs. If an attacker could observe outputs and work out the base, as in a server hashing untrusted input, draw it from secrets.randbelow and keep it private.
Exercise
You use mod = 1000 and base = 10 to hash strings of digits. Explain why "98765" and "12765" get the same hash, and name the rule that was broken.
Show answer
The weight of position i is 10^(m-1-i) mod 1000. For i = 0 and i = 1 the weights are 10^4 and 10^3, and both are 0 modulo 1000. Only the last three characters "765" contribute, so both strings hash the same. The rule broken is gcd(base, mod) = 1: 10 and 1000 share factors. A prime modulus would have prevented this.
Exercise
You scan a text of n = 10^7 characters for a pattern of m = 10^4 characters, using a random base and p = 10^9 + 7. Bound the expected number of false-positive hash matches. Is it acceptable?
Show answer
The bound is n(m - 1)/p ≈ 10^7 · 10^4 / 10^9 = 100 false positives. Each one costs an O(m) = 10^4 comparison, about 10^6 extra operations in total. That is small next to the 10^7-step scan, so it is acceptable. Switching to 2^61 - 1 would bring it to about 4·10^-8.
Exercise
Why doesn't drawing a random odd base protect a hash that uses unsigned 64-bit overflow as its modulus?
Show answer
The collision bound needs the arithmetic to happen in a field, which requires a prime modulus. Then a nonzero difference polynomial has at most m - 1 roots. Modulo 2^64 that argument fails. Thue–Morse strings make the difference polynomial vanish for every odd base, so no random choice of odd base avoids the collision.