Sub topic 11
Prefix Hashes: Any Substring Hash in O(1)
This chapter assumes you already know the polynomial hash and the rolling update from earlier chapters, and that you are comfortable with Python's % operator. The rolling hash only moves one window forward one step at a time. Many problems need the hash of an arbitrary substring s[i:j], chosen in any order. Prefix hashes give you that after a single O(n) precomputation.
The idea: hash every prefix once
Define h[k] as the polynomial hash of the first k characters, s[0:k]. Horner's rule builds each prefix from the one before it:
h[0] = 0h[k + 1] = h[k] * B + s[k]
Alongside it, store the powers p[k] = B^k. Both arrays have length n + 1, and both are reduced modulo M.
Deriving the substring formula
Use base 10 and digit values so the arithmetic is easy to see. For s = "31415":
| k | prefix | h[k] |
|---|---|---|
| 0 | "" | 0 |
| 1 | "3" | 3 |
| 2 | "31" | 31 |
| 3 | "314" | 314 |
| 4 | "3141" | 3141 |
| 5 | "31415" | 31415 |
Suppose you want the hash of s[1:4] = "141". h[4] = 3141 contains the leading 3, which has been shifted left three places since it was added. Remove it by subtracting h[1] * 10^3 = 3000. That leaves 141.
In general, h[j] equals h[i] shifted left by j - i positions, plus the hash of s[i:j]. Rearranging gives:
hash(s[i:j]) = (h[j] - h[i] * p[j - i]) mod M
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. After that, each query costs one multiplication, one subtraction, and one reduction.
Common errors
- Wrong power. Multiplying by
p[i]instead ofp[j - i]is the most frequent bug. The shift depends on the length of the substring, not on where it starts. - Off-by-one indexing.
hhasn + 1entries, andh[k]coverss[0:k]. A query fors[i:j]readsh[i]andh[j]directly, with no- 1. - Comparing different lengths. Equal hashes only suggest equality when the two substrings have the same length. Check the lengths first.
- Trusting a match. Collisions still happen. Verify with a direct comparison when correctness matters, or use double hashing.
Exercise
Using base 10 and digit values, with s = "31415", compute the hash of s[2:5] from the prefix table. Then explain why multiplying h[2] by p[2] would give the wrong answer.
Show answer
hash = h[5] - h[2] 10^(5-2) = 31415 - 31 1000 = 415, which matches "415". Using p[2] = 100 gives 31415 - 3100 = 28315. That is wrong because the prefix "31" has been shifted by the substring's length (3 positions), not by its start index (2).
Exercise
Write a function same(h, p, a, b, L) that returns True when the hashes of s[a:a+L] and s[b:b+L] are equal.
Show answer
def same(h, p, a, b, L): return substringhash(h, p, a, a + L) == substringhash(h, p, b, b + L)