Polynomial Hashing in Depth
Collision probabilities, double hashing and comparing substrings in O(1).
Polynomial hashing compares any two substrings of a string in after preprocessing, and it powers the shortest solutions to dozens of string problems. Its guarantee lives entirely in a random choice. Fix the base and let the arithmetic overflow modulo , and two strings of length 1024 from a sequence studied over a century ago collide for every odd base.
What you’ll learn
- Compute the hash of any substring in from prefix hashes, and compare substrings by equality and by longest common prefix.
- Prove that two distinct strings of length collide with probability at most for a random base, and combine it with union and birthday bounds.
- Prove that hashing modulo fails on Thue–Morse strings for every odd base, and choose safe parameters.
- Design hashing algorithms: longest common substring by binary search, substring comparison, and Karp–Rabin fingerprints with random primes.
Prefix hashes and O(1) substrings
Fix a prime and a base , and map characters to integers in . The polynomial hash of is
computed by Horner's rule, one multiplication and one addition per character. Store the prefix hashes and , together with the powers .
Horner's rule run over first computes and then multiplies it by once for each of the remaining characters, while those characters form their own hash:
Solve for the substring (half-open, ):
import random
MOD = (1 << 61) - 1 # a Mersenne prime
class PolyHash:
"""H(s[l:r]) in O(1) after O(n) preprocessing; the base is drawn at run time."""
base = random.randrange(10**6, MOD - 1)
def __init__(self, s):
b = self.base
self.pre = [0] * (len(s) + 1) # pre[i] = H(s[:i])
self.pw = [1] * (len(s) + 1) # pw[i] = b^i mod MOD
for i, ch in enumerate(s):
self.pre[i + 1] = (self.pre[i] * b + ord(ch)) % MOD
self.pw[i + 1] = self.pw[i] * b % MOD
def get(self, l, r): # hash of s[l:r], half-open
return (self.pre[r] - self.pre[l] * self.pw[r - l]) % MODEvery string hashed in one run shares the class-level base, so hashes of different strings are comparable. In C++, reduce a 122-bit product modulo with a 128-bit multiplication and the identity ; Python's integers do it exactly.
Equal substrings always have equal hashes; unequal ones have equal hashes only by a collision. So "is ?" takes , and the length of the longest common prefix of two suffixes takes by binary search on , which also compares two substrings lexicographically: find the first differing position, then compare one character.
The collision bound
The hashes agree exactly when is a root of the difference polynomial over the field :
Some , and both are below , so that coefficient is nonzero modulo : is a nonzero polynomial of degree at most . A nonzero polynomial over a field has at most as many roots as its degree, so at most of the equally likely bases are bad:
Many comparisons. For comparisons of pairs fixed in advance, a union bound gives failure probability at most . With , and :
The bound holds for every pair fixed before is drawn; a typical pair collides with probability about . A 30-bit prime such as gives a per-comparison bound of for , and over comparisons the union bound says nothing at all. Two independent bases with two such primes multiply the per-comparison bounds, about , or over comparisons: better, but a single 61-bit prime is simpler and safer.
The birthday paradox bites when you look for any equal pair, for example by putting the hashes of all windows of one length into a hash set. With strings there are pairs, so even perfectly random hash values collide once approaches .
You put the hashes of all windows of length of a string into a hash set, using one modulus . Even if the hash values were perfectly random, how many colliding pairs would you expect?
Show the answer
5 pairs
Each of the pairs collides with probability about , so about collisions are expected, and a "repeated substring" answer would very likely be wrong. With the expectation drops to about ; even the worst-case bound stays near for .
Breaking fixed parameters: Thue–Morse and 2⁶⁴
Everything above assumed a base drawn after the strings were fixed. If the base and modulus are fixed and known, an opponent can search for collisions. By the birthday paradox, a few tens of thousands of random strings collide modulo , a fraction of a second of computing. A tempting shortcut is to skip the modulus altogether and let 64-bit unsigned arithmetic overflow, which computes modulo for free. It fails for a deeper reason: is not prime, and powers of an odd base pile up factors of two.
Concatenation. For strings , . Apply it to and , whose halves have length :
Unroll. Starting from :
Count the twos. For odd , divides : for because is even, and inductively because with an even second factor. Multiply over :
Collide. For , . Mapping 0 and 1 to any two character codes multiplies the difference by a constant, and reversing gives or , so the left-to-right hash above collides too. Two strings of length 2048 have equal 64-bit hashes for every odd base:
A sharper count makes it worse. Every odd satisfies , so in fact divides for , and already reaches 64 factors of two: strings of length 1024 collide for every odd base, as a quick computation over random bases confirms. Even bases are worse still: , so with the left-to-right hash only the last 64 characters matter. Pachocki and Radoszewski also note that the attack survives "spot checks" of a few random positions, by padding the strings with long runs of one character.
You hash with unsigned 64-bit overflow, but draw an odd base at random at run time. An opponent knows your code but not your base. Are you safe?
- Yes: with a random base, a fixed pair collides with probability about
- No: the Thue–Morse strings of length 1024 collide for every odd base, so the opponent needs no knowledge of the base
- Yes, provided the base is even
- No, but only because the opponent can guess the base by brute force
Show the answer
B. No: the Thue–Morse strings of length 1024 collide for every odd base, so the opponent needs no knowledge of the base
The difference of the two hashes is , which is divisible by for every odd once . The root-counting bound needs a prime modulus: modulo the "polynomial" can vanish for every odd base at once. Use a prime such as .
The defenses are simple: a prime modulus such as and a base drawn at run time; or two independent bases with two primes near if 64-bit products are all you have. Never rely on overflow modulo when inputs can be adversarial, as with hacking phases in programming contests. The Optimal lesson Hash Flooding & Anti-Hash Tests covers the same war for hash tables.
Algorithms built on hashing
The longest common substring of and has no fixed pattern to search for, but its length is a binary search on the answer: if a common substring of length exists, its prefix of length is common too. For a given , put the hashes of all length- windows of in a set and test the windows of .
import random
MOD = (1 << 61) - 1
B = random.randrange(10**6, MOD - 1)
def prefix_hashes(s):
pre = [0]
for ch in s:
pre.append((pre[-1] * B + ord(ch)) % MOD)
return pre
def longest_common_substring(s, t):
pw = [1]
for _ in range(max(len(s), len(t))):
pw.append(pw[-1] * B % MOD)
ps, pt = prefix_hashes(s), prefix_hashes(t)
def sub(pre, i, L): # hash of the length-L window at i
return (pre[i + L] - pre[i] * pw[L]) % MOD
def common(L): # some length-L substring of s occurs in t?
seen = {sub(ps, i, L) for i in range(len(s) - L + 1)}
return any(sub(pt, j, L) in seen for j in range(len(t) - L + 1))
lo, hi = 0, min(len(s), len(t)) # invariant: common(lo) is true
while lo < hi:
mid = (lo + hi + 1) // 2
if common(mid):
lo = mid
else:
hi = mid - 1
return lo expected time. A collision can only make common wrongly true, so the answer is never too small, and it is too large with probability bounded as in the previous step; checking the witness characters makes it exact. Suffix structures solve the problem deterministically in linear time.
The same toolkit gives a quick suffix array, sorting suffixes with a comparator that finds their longest common prefix by binary search on hashes, in ; palindrome tests for any substring in , comparing the forward hash with the hash of the reversed string (see Palindromes: Manacher's Algorithm & the Eertree); matching of many patterns of one length by a hash set of their hashes; and two-dimensional matching by hashing rows, then columns.
Rolling fingerprints run far outside textbooks. Content-defined chunking in backup and file-synchronization systems cuts files where a rolling hash of the last few dozen bytes hits a pattern, so an insertion shifts only nearby chunk boundaries (the Low-Bandwidth File System of Muthitacharoen, Chen and Mazières, 2001, used Rabin's polynomial fingerprints). Plagiarism detectors such as MOSS select fingerprints of -grams by winnowing (Schleimer, Wilkerson & Aiken, 2003). And the message authentication codes GHASH, inside AES-GCM, and Poly1305 evaluate the message as a polynomial at a secret point: their forgery bound is the same root count as above, with a field of about or elements.
The frontier
Key takeaways
- Prefix hashes give in , so substring equality costs and a longest common prefix or a lexicographic comparison .
- With a random base modulo a prime , distinct strings of length collide with probability at most , because a nonzero polynomial of degree at most has at most roots; union bounds cover many comparisons, and birthday effects make a 30-bit modulus unsafe for large sets of hashes.
- Fixed or overflow-based parameters can be attacked: modulo the Thue–Morse strings of length 1024 collide for every odd base. Use a prime such as with a base drawn at run time.
- Hashing turns string problems into binary searches and set lookups, such as the longest common substring in expected time; Karp–Rabin's random-prime fingerprints and polynomial MACs rest on the same counting of roots or prime factors.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Two distinct strings of length 1000 are hashed with a uniformly random base modulo the prime . What is the best guaranteed bound on their collision probability?
Show the answer
C.
The difference of the two hashes is a nonzero polynomial in of degree at most 999, with at most 999 roots among the bases. is the typical rate for a random pair but is not guaranteed for every pair.
A contestant maps and stores the hashes of many strings of different lengths in one set. Which pair always collides, whatever the base and modulus?
- and
- and
- and
- None: a random base prevents all collisions
Show the answer
A. and
With , : a leading zero digit does not change a number. Map characters to nonzero values and compare lengths too.
Why may you binary search on the length when looking for the longest common substring of two strings?
- Because polynomial hashes grow with the length of the string
- Because the strings must be sorted first
- Because hashing makes every length- test exact
- Because if a common substring of length exists, one of every length below exists too
Show the answer
D. Because if a common substring of length exists, one of every length below exists too
The predicate "some common substring has length " is monotone: true up to the answer and false beyond it, since prefixes of a common substring are common. Binary search needs only this monotonicity; hashing makes each test expected.
In Karp–Rabin fingerprinting, two distinct -bit numbers are compared modulo a prime drawn uniformly from the primes up to . Why is a false match unlikely?
- A false match needs to divide their difference, which has fewer than distinct prime factors, while there are about primes to choose from
- Their difference is always prime
- Reducing modulo a prime preserves every bit of the numbers
- Distinct numbers can never be congruent modulo a prime larger than
Show the answer
A. A false match needs to divide their difference, which has fewer than distinct prime factors, while there are about primes to choose from
exactly when divides , a nonzero number below with fewer than prime factors. So at most of the candidate primes are bad, and taking polynomial in makes the error polynomially small.
Further reading
- R. M. Karp & M. O. Rabin, "Efficient randomized pattern-matching algorithms," IBM Journal of Research and Development 31(2) (1987), 249–260.
- J. Pachocki & J. Radoszewski, "Where to use and how not to use polynomial string hashing," Olympiads in Informatics 7 (2013), 90–100.
- E. Porat & B. Porat, "Exact and approximate pattern matching in the streaming model," Proceedings of IEEE FOCS (2009), 315–323.
- M. Thorup, "High speed hashing for integers and strings," lecture notes, arXiv:1504.06804 (2015).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), section 32.2.