Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Polynomial Hashing in Depth

Collision probabilities, double hashing and comparing substrings in O(1).

Polynomial hashing compares any two substrings of a string in O(1)O(1) after O(n)O(n) 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 2642^{64}, 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 O(1)O(1) from prefix hashes, and compare substrings by equality and by longest common prefix.
  • Prove that two distinct strings of length nn collide with probability at most (n−1)/p(n-1)/p for a random base, and combine it with union and birthday bounds.
  • Prove that hashing modulo 2642^{64} 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 pp and a base b∈Zpb \in \Z_p, and map characters to integers in [1,p)[1, p). The polynomial hash of s=s0s1⋯sn−1s = s_0 s_1 \cdots s_{n-1} is

H(s)=(∑i=0n−1si b n−1−i) mod p,H(s) = \Big(\sum_{i=0}^{n-1} s_i\, b^{\,n-1-i}\Big) \bmod p,

computed by Horner's rule, one multiplication and one addition per character. Store the prefix hashes P[0]=0P[0] = 0 and P[i+1]=(P[i]⋅b+si) mod pP[i+1] = (P[i]\cdot b + s_i) \bmod p, together with the powers bi mod pb^i \bmod p.

DerivationThe hash of any substring
  1. P[r]≡P[l]⋅b r−l+H(s[l..r))(modp)P[r] \equiv P[l]\cdot b^{\,r-l} + H\big(s[l..r)\big) \pmod p

    Horner's rule run over s[0..r)s[0..r) first computes P[l]P[l] and then multiplies it by bb once for each of the r−lr - l remaining characters, while those characters form their own hash:

  2. H(s[l..r))=(P[r]−P[l]⋅b r−l) mod pH\big(s[l..r)\big) = \big(P[r] - P[l]\cdot b^{\,r-l}\big) \bmod p

    Solve for the substring (half-open, 0≤l≤r≤n0 \le l \le r \le n):

python
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]) % MOD

Every 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 261−12^{61} - 1 with a 128-bit multiplication and the identity 261≡12^{61} \equiv 1; Python's integers do it exactly.

Equal substrings always have equal hashes; unequal ones have equal hashes only by a collision. So "is s[i..i+L)=s[j..j+L)s[i..i+L) = s[j..j+L)?" takes O(1)O(1), and the length of the longest common prefix of two suffixes takes O(log⁡n)O(\log n) by binary search on LL, which also compares two substrings lexicographically: find the first differing position, then compare one character.

The collision bound

DerivationProof: count the roots
  1. D(b)=∑i=0n−1(xi−yi) b n−1−i≡0(modp)D(b) = \sum_{i=0}^{n-1} (x_i - y_i)\, b^{\,n-1-i} \equiv 0 \pmod p

    The hashes agree exactly when bb is a root of the difference polynomial over the field Zp\Z_p:

  2. Pr⁡[D(b)=0] ≤ n−1p\Pr[D(b) = 0] \ \le\ \frac{n-1}{p}

    Some xi≠yix_i \ne y_i, and both are below pp, so that coefficient is nonzero modulo pp: DD is a nonzero polynomial of degree at most n−1n-1. A nonzero polynomial over a field has at most as many roots as its degree, so at most n−1n-1 of the pp equally likely bases are bad:

  3. Pr⁡[any collision] ≤ 106⋅1052.3×1018 ≈ 4.3×10−8\Pr[\text{any collision}] \ \le\ \frac{10^6 \cdot 10^5}{2.3 \times 10^{18}} \ \approx\ 4.3 \times 10^{-8}

    Many comparisons. For qq comparisons of pairs fixed in advance, a union bound gives failure probability at most q(n−1)/pq(n-1)/p. With p=261−1≈2.3×1018p = 2^{61}-1 \approx 2.3\times10^{18}, q=106q = 10^6 and n=105n = 10^5:

The bound (n−1)/p(n-1)/p holds for every pair fixed before bb is drawn; a typical pair collides with probability about 1/p1/p. A 30-bit prime such as 109+710^9 + 7 gives a per-comparison bound of 10−410^{-4} for n=105n = 10^5, and over 10610^6 comparisons the union bound says nothing at all. Two independent bases with two such primes multiply the per-comparison bounds, about 10−810^{-8}, or 10−210^{-2} over 10610^6 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 NN strings there are (N2)\binom N2 pairs, so even perfectly random hash values collide once NN approaches p\sqrt p.

Predict before you look

You put the hashes of all 10510^5 windows of length LL of a string into a hash set, using one modulus p≈109p \approx 10^9. Even if the hash values were perfectly random, how many colliding pairs would you expect?

Show the answer

5 pairs

Each of the (1052)≈5×109\binom{10^5}{2} \approx 5 \times 10^9 pairs collides with probability about 10−910^{-9}, so about 55 collisions are expected, and a "repeated substring" answer would very likely be wrong. With p=261−1p = 2^{61}-1 the expectation drops to about 2×10−92 \times 10^{-9}; even the worst-case bound (1052)(L−1)/p\binom{10^5}{2}(L-1)/p stays near 2×10−42 \times 10^{-4} for L=105L = 10^5.

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 109+710^9 + 7, 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 2642^{64} for free. It fails for a deeper reason: 2642^{64} is not prime, and powers of an odd base pile up factors of two.

DerivationProof
  1. W(τˉk)−W(τk)=(1−b2k−1)(W(τˉk−1)−W(τk−1))W(\bar\tau_k) - W(\tau_k) = \big(1 - b^{2^{k-1}}\big)\big(W(\bar\tau_{k-1}) - W(\tau_{k-1})\big)

    Concatenation. For strings u,vu, v, W(uv)=W(u)+b∣u∣ W(v)W(uv) = W(u) + b^{\abs u}\,W(v). Apply it to τk=τk−1τˉk−1\tau_k = \tau_{k-1}\bar\tau_{k-1} and τˉk=τˉk−1τk−1\bar\tau_k = \bar\tau_{k-1}\tau_{k-1}, whose halves have length 2k−12^{k-1}:

  2. W(τˉk)−W(τk)=∏i=0k−1(1−b2i)W(\bar\tau_k) - W(\tau_k) = \prod_{i=0}^{k-1}\big(1 - b^{2^i}\big)

    Unroll. Starting from W(τˉ0)−W(τ0)=1−0=1W(\bar\tau_0) - W(\tau_0) = 1 - 0 = 1:

  3. 2 1+2+⋯+k=2 k(k+1)/2 ∣ W(τˉk)−W(τk)2^{\,1 + 2 + \cdots + k} = 2^{\,k(k+1)/2} \ \Big|\ W(\bar\tau_k) - W(\tau_k)

    Count the twos. For odd bb, 2i+12^{i+1} divides b2i−1b^{2^i} - 1: for i=0i = 0 because b−1b - 1 is even, and inductively because b2i−1=(b2i−1−1)(b2i−1+1)b^{2^i} - 1 = (b^{2^{i-1}} - 1)(b^{2^{i-1}} + 1) with an even second factor. Multiply over i=0,…,k−1i = 0, \dots, k-1:

  4. H(τ11)≡H(τˉ11)(mod264)H(\tau_{11}) \equiv H(\bar\tau_{11}) \pmod{2^{64}}

    Collide. For k=11k = 11, k(k+1)/2=66≥64k(k+1)/2 = 66 \ge 64. Mapping 0 and 1 to any two character codes multiplies the difference by a constant, and reversing τk\tau_k gives τk\tau_k or τˉk\bar\tau_k, 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 bb satisfies b2≡1(mod8)b^2 \equiv 1 \pmod 8, so in fact 2i+22^{i+2} divides b2i−1b^{2^i} - 1 for i≥1i \ge 1, and k=10k = 10 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: b64≡0(mod264)b^{64} \equiv 0 \pmod{2^{64}}, 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.

Check your understanding

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?

  1. Yes: with a random base, a fixed pair collides with probability about 2−642^{-64}
  2. No: the Thue–Morse strings of length 1024 collide for every odd base, so the opponent needs no knowledge of the base
  3. Yes, provided the base is even
  4. 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 ∏i<k(1−b2i)\prod_{i<k}(1 - b^{2^i}), which is divisible by 2642^{64} for every odd bb once k≥10k \ge 10. The root-counting bound needs a prime modulus: modulo 2642^{64} the "polynomial" can vanish for every odd base at once. Use a prime such as 261−12^{61} - 1.

The defenses are simple: a prime modulus such as 261−12^{61}-1 and a base drawn at run time; or two independent bases with two primes near 10910^9 if 64-bit products are all you have. Never rely on overflow modulo 2642^{64} 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 ss and tt has no fixed pattern to search for, but its length is a binary search on the answer: if a common substring of length LL exists, its prefix of length L−1L - 1 is common too. For a given LL, put the hashes of all length-LL windows of ss in a set and test the windows of tt.

python
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

O((n+m)log⁡min⁡(n,m))O((n+m)\log\min(n,m)) 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 O(nlog⁡2n)O(n\log^2 n); palindrome tests for any substring in O(1)O(1), 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 kk-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 21282^{128} or 21302^{130} elements.

The frontier

Key takeaways

  • Prefix hashes give H(s[l..r))=(P[r]−P[l] b r−l) mod pH(s[l..r)) = (P[r] - P[l]\,b^{\,r-l}) \bmod p in O(1)O(1), so substring equality costs O(1)O(1) and a longest common prefix or a lexicographic comparison O(log⁡n)O(\log n).
  • With a random base modulo a prime pp, distinct strings of length nn collide with probability at most (n−1)/p(n-1)/p, because a nonzero polynomial of degree at most n−1n-1 has at most n−1n-1 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 2642^{64} the Thue–Morse strings of length 1024 collide for every odd base. Use a prime such as 261−12^{61}-1 with a base drawn at run time.
  • Hashing turns string problems into binary searches and set lookups, such as the longest common substring in O(nlog⁡n)O(n\log n) 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.

Question 1

Two distinct strings of length 1000 are hashed with a uniformly random base modulo the prime p=109+7p = 10^9 + 7. What is the best guaranteed bound on their collision probability?

  1. 1/p≈10−91/p \approx 10^{-9}
  2. 10002/p≈10−31000^2/p \approx 10^{-3}
  3. 999/p≈10−6999/p \approx 10^{-6}
  4. 2−642^{-64}
Show the answer

C. 999/p≈10−6999/p \approx 10^{-6}

The difference of the two hashes is a nonzero polynomial in bb of degree at most 999, with at most 999 roots among the pp bases. 1/p1/p is the typical rate for a random pair but is not guaranteed for every pair.

Question 2

A contestant maps a↦0,b↦1,…\texttt{a} \mapsto 0, \texttt{b} \mapsto 1, \dots and stores the hashes of many strings of different lengths in one set. Which pair always collides, whatever the base and modulus?

  1. b\texttt{b} and ab\texttt{ab}
  2. ab\texttt{ab} and ba\texttt{ba}
  3. ab\texttt{ab} and abb\texttt{abb}
  4. None: a random base prevents all collisions
Show the answer

A. b\texttt{b} and ab\texttt{ab}

With a=0\texttt{a} = 0, H(ab)=0⋅b+1=H(b)H(\texttt{ab}) = 0 \cdot b + 1 = H(\texttt{b}): a leading zero digit does not change a number. Map characters to nonzero values and compare lengths too.

Question 3

Why may you binary search on the length when looking for the longest common substring of two strings?

  1. Because polynomial hashes grow with the length of the string
  2. Because the strings must be sorted first
  3. Because hashing makes every length-LL test exact
  4. Because if a common substring of length LL exists, one of every length below LL exists too
Show the answer

D. Because if a common substring of length LL exists, one of every length below LL exists too

The predicate "some common substring has length LL" 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 O(n+m)O(n + m) expected.

Question 4

In Karp–Rabin fingerprinting, two distinct nn-bit numbers are compared modulo a prime pp drawn uniformly from the primes up to MM. Why is a false match unlikely?

  1. A false match needs pp to divide their difference, which has fewer than nn distinct prime factors, while there are about M/ln⁡MM/\ln M primes to choose from
  2. Their difference is always prime
  3. Reducing modulo a prime preserves every bit of the numbers
  4. Distinct numbers can never be congruent modulo a prime larger than nn
Show the answer

A. A false match needs pp to divide their difference, which has fewer than nn distinct prime factors, while there are about M/ln⁡MM/\ln M primes to choose from

x≡y(modp)x \equiv y \pmod p exactly when pp divides ∣x−y∣\abs{x - y}, a nonzero number below 2n2^n with fewer than nn prime factors. So at most nn of the π(M)≈M/ln⁡M\pi(M) \approx M/\ln M candidate primes are bad, and taking MM polynomial in nn 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.