Sub topic 11
Prefix Hashes: Any Substring Hash in O(1)
The rolling hash from earlier chapters is fast, but it only moves forward. It gives you the hash of window 0, then window 1, then window 2, each in constant time, and only in that order. Many problems need random access instead. They ask "is s[3:9] equal to s[17:23]?" for arbitrary positions, often thousands of times. A prefix-hash table answers each such question in O(1) after O(n) preprocessing.
This chapter assumes you are comfortable with the polynomial hash computed by Horner's rule, modular arithmetic (including how Python's % treats negative numbers), and Python slicing, where s[i:j] covers indices i through j - 1.
The Idea: Store Every Prefix Hash
Define h[k] as the polynomial hash of the first k characters, s[0:k]. Horner's rule already computes these values one after another as it scans the string, so we keep each intermediate result instead of throwing it away:
h[0] = 0(the empty prefix)h[k + 1] = (h[k] * B + s[k]) mod M
Written out without the modulus, the prefix hash is
h[k] = s[0]·B^(k-1) + s[1]·B^(k-2) + ... + s[k-1]·B^0
The first character carries the highest power. Each time a character is appended, everything already in the hash shifts up one power of B.
Deriving the substring formula
We want the hash of s[i:j], which by definition is
H(i, j) = s[i]·B^(j-i-1) + s[i+1]·B^(j-i-2) + ... + s[j-1]·B^0
Now split h[j] into two parts: the characters before i and the characters from i to j - 1.
h[j] = (s[0]·B^(j-1) + ... + s[i-1]·B^(j-i)) + (s[i]·B^(j-i-1) + ... + s[j-1])
The second group is exactly H(i, j). The first group is h[i], but every term in it has been shifted up by j - i further positions. So it equals h[i] · B^(j-i). Subtracting gives
H(i, j) = (h[j] - h[i] · B^(j-i)) mod M
The formula needs B^(j-i) in constant time, so we precompute a powers table p[k] = B^k mod M alongside h.
A hand-sized example
Use base 10, no modulus, and the values a=1, b=2, c=3 so the numbers stay readable. For s = "abc":
| k | prefix `s[0:k]` | `h[k]` | `p[k]` |
|---|---|---|---|
| 0 | "" | 0 | 1 |
| 1 | "a" | 1 | 10 |
| 2 | "ab" | 12 | 100 |
| 3 | "abc" | 123 | 1000 |
The hash of s[1:3], which is "bc", is h[3] - h[1]·p[2] = 123 - 1·100 = 23. That matches hashing "bc" directly: 2·10 + 3 = 23. In base 10 the subtraction removes the leading digits, and modular arithmetic does the same thing with a different number system.
Implementation
def build_prefix(s, base=256, mod=1_000_000_007):
h = [0] * (len(s) + 1)
p = [1] * (len(s) + 1)
for i, ch in enumerate(s):
h[i + 1] = (h[i] * base + ord(ch)) % mod
p[i + 1] = (p[i] * base) % mod
return h, p
def substring_hash(h, p, i, j, mod=1_000_000_007):
"""Hash of s[i:j]."""
return (h[j] - h[i] * p[j - i]) % mod
h, p = build_prefix("banana")
print(substring_hash(h, p, 1, 4) == substring_hash(h, p, 3, 6)) # 'ana' == 'ana' -> TrueBuilding the tables takes O(n) time and O(n) memory. Each query does one multiplication, one subtraction, and one modulo.
The subtraction can go negative, because h[i] * p[j - i] reduced mod M may be larger than h[j]. Python's % always returns a value in [0, M) for a positive modulus, so the code above is correct as written. In Java or C++, % keeps the sign of the dividend, so you must write ((h[j] - h[i] * p[j - i] % M) % M + M) % M with 64-bit integers. The overflow chapter covers the details.
Rolling Hash vs. Prefix Hashes
Both techniques rest on the same polynomial. They differ in what they store and which queries they serve.
| Approach | Preprocessing | Per query | Extra memory | Query pattern |
|---|---|---|---|---|
| Hash the slice directly | none | O(length) | O(1) | any |
| Rolling hash | O(m) | O(1) | O(1) | sequential windows of one fixed length |
| Prefix hashes | O(n) | O(1) | O(n) | any `(i, j)`, any length, any order |
Rabin-Karp over one long text with a single pattern needs only the rolling hash. Prefix hashes are the better choice when queries jump around, when window lengths change (as in binary search over lengths), or when you compare substrings of one string against each other.
Application: O(1) Palindrome Checks
A substring is a palindrome when it equals its own reverse. Build prefix hashes for both s and r = s[::-1]. The reverse of s[i:j] occupies r[n-j:n-i], so comparing two O(1) hashes answers each palindrome query.
MOD = 1_000_000_007
BASE = 911_382_323
def build(s):
h = [0] * (len(s) + 1)
p = [1] * (len(s) + 1)
for i, ch in enumerate(s):
h[i + 1] = (h[i] * BASE + ord(ch)) % MOD
p[i + 1] = (p[i] * BASE) % MOD
return h, p
def sub(h, p, i, j):
return (h[j] - h[i] * p[j - i]) % MOD
class PalChecker:
def __init__(self, s):
self.n = len(s)
self.fh, self.p = build(s)
self.rh, _ = build(s[::-1])
def is_palindrome(self, i, j):
"""True (with high probability) if s[i:j] is a palindrome."""
n = self.n
return sub(self.fh, self.p, i, j) == sub(self.rh, self.p, n - j, n - i)
pc = PalChecker("abacabad")
print(pc.is_palindrome(0, 7)) # 'abacaba' -> True
print(pc.is_palindrome(1, 4)) # 'bac' -> False
print(pc.is_palindrome(3, 4)) # 'c' -> TrueThis code uses a large base instead of 256. With base 256 and a small alphabet, many distinct strings map to small, structured numbers, and a larger base close to the modulus spreads them out better. The parameter-choice chapter explains why the base should ideally be random.
Edge Cases and Common Errors
Empty substrings
When i == j, the formula returns h[i] - h[i]·1 = 0. That result is consistent: every empty substring hashes to 0 and every pair compares equal. Validate 0 <= i <= j <= n at the call site. Python's negative indexing turns an out-of-range i into a silently wrong answer instead of an error.
Comparing substrings of different lengths
The polynomial hash has no length marker. If any character value can be 0, a leading zero adds nothing: "\x00a" and "a" both hash to 97. Real text rarely contains NUL, but binary data and arrays of small integers often do. Two fixes work:
- Compare only substrings of equal length. Check
j1 - i1 == j2 - i2first, which is free and also catches obvious mismatches early. - Map every symbol to a value in
[1, B), for exampleord(ch) + 1with the base larger than the biggest mapped value.
When a symbol's value is at least B, the representation stops being a clean base-B number and unrelated strings collide more often. Keep B larger than your alphabet.
Mixing tables
Two hashes are only comparable when they come from the same base and modulus. A frequent bug builds the second string's table with different default parameters, or with a different random base, and then compares hashes across strings. Draw the random base once and share it between all tables.
Off-by-one indices
h has length n + 1, and h[k] covers s[0:k], not s[0:k+1]. Using half-open intervals [i, j) everywhere, as Python slicing does, removes most off-by-one errors. Convert any inclusive [l, r] input to [l, r + 1) once, at the boundary.
Memory on huge inputs
Two Python lists of length n + 1 hold arbitrary-precision integers, about 28 bytes each plus an 8-byte pointer. For 10^7 characters that is several hundred megabytes. Use array('q') or NumPy int64 arrays, which work because every stored value is below the modulus, or fall back to the rolling hash if you only need sequential windows.
Where This Leads
With O(1) substring comparison you can find the longest common prefix of two suffixes by binary search on the length, in O(log n) per query. That primitive drives the longest-repeated-substring technique in a later chapter. It also supports sorting suffixes by comparison and counting distinct substrings of a fixed length with a set of hashes.
Exercise
Using base 10, no modulus, and the values a=1, b=2, c=3 with s = "abcab", compute h[2], h[5], and p[3], then use the prefix formula to get the hash of s[2:5]. Check your result by hashing "cab" directly.
Show answer
h[2] = 12 and h[5] = 12312, and p[3] = 1000. H(2, 5) = 12312 - 12·1000 = 312. Hashing "cab" directly gives 3·100 + 1·10 + 2 = 312, which agrees.
Exercise
A teammate's code says substringhash(h, p, 0, 2) == substringhash(h, p, 1, 2) is True for the list [0, 5] encoded with chr, using build_prefix with base 256. Explain why, and give two ways to fix it.
Show answer
The value 0 contributes nothing, so [0, 5] hashes to 0·256 + 5 = 5, the same as [5]. The fixes are to compare only substrings of equal length, or to map every symbol to a nonzero value such as value + 1 while keeping the base larger than the largest mapped value.
Exercise
You must answer 10^5 queries, each asking whether s[a:a+L] == s[b:b+L], where L differs from query to query, on a string of length 10^6. Which technique fits, and what is the total running time?
Show answer
Prefix hashes fit, because the lengths vary and the positions arrive in arbitrary order, which a single rolling hash cannot serve. Preprocessing takes O(n) = 10^6 steps and each query takes O(1), so the total is O(n + q), about 1.1 × 10^6 operations. Double hashing or verification is optional and depends on how costly a false positive would be.