Sub topic 3
Avoiding Overflow, Double Hashing, and Advanced Uses of Rolling Hashes
This chapter assumes you already know the polynomial hash, the rolling update, and Rabin-Karp with match verification from the earlier chapters.
Avoiding Overflow and Negative Remainders in Java and C++
Python integers never overflow. In Java and C++, though, the product hash * BASE overflows if you store it in a 32-bit type. Keep every value below MOD, and use 64-bit long so that a product of two values below about 3×10⁹ still fits. There is a second trap: % in both languages can return a negative result. Add MOD before you reduce.
public class Roll {
static final long MOD = 1_000_000_007L, BASE = 256L;
static long roll(long hash, char out, char in, long high) {
long next = (hash - out * high % MOD + MOD) % MOD;
return (next * BASE + in) % MOD;
}
public static void main(String[] args) {
long high = BASE % MOD; // BASE^(m-1) for m = 2
long h = ('a' * BASE + 'b') % MOD; // hash("ab")
System.out.println(roll(h, 'a', 'c', high) == ('b' * BASE + 'c') % MOD); // true
}
}Double Hashing to Cut Collision Probability
You can compute two hashes with independent moduli and compare them as a pair. Two unequal strings then collide with probability about 1/(M₁·M₂) instead of 1/M. The cost is roughly twice the arithmetic per step.
Prefix Hashes and Longest Repeated Substring
Store h[i], the hash of s[:i], together with the powers p[i]. The hash of s[i:j] is then (h[j] - h[i]*p[j-i]) % mod, which takes O(1) time. To find the longest repeated substring, binary search on the length L. The search works because if some length-L substring repeats, a shorter repeated substring exists too.
def longest_repeat(s, base=911382323, mod=(1 << 61) - 1):
n = len(s)
h, p = [0] * (n + 1), [1] * (n + 1)
for i, ch in enumerate(s):
h[i + 1] = (h[i] * base + ord(ch)) % mod
p[i + 1] = p[i] * base % mod
def find(L):
seen = {}
for i in range(n - L + 1):
v = (h[i + L] - h[i] * p[L]) % mod
j = seen.get(v)
if j is not None and s[j:j + L] == s[i:i + L]:
return i
seen.setdefault(v, i)
return -1
lo, hi, best = 1, n - 1, ""
while lo <= hi:
mid = (lo + hi) // 2
i = find(mid)
if i >= 0:
best, lo = s[i:i + mid], mid + 1
else:
hi = mid - 1
return best
print(longest_repeat("banana")) # anaThe expected running time is O(n log n).
Many Patterns of the Same Length
Put the hash of every pattern in a dictionary. Roll one window over the text, look up each window hash in the dictionary, and verify any hit by comparing the strings directly. Each window costs O(1) expected time, however many patterns you have.
Anti-Hash Tests and Rabin Fingerprints
| Topic | Key point |
|---|---|
| Anti-hash inputs | When the base and modulus are fixed, an attacker can build strings that collide. A common case is mod 2⁶⁴ via natural overflow, which Thue–Morse strings break. Pick the base at random at runtime and use a large prime modulus. |
| Rabin fingerprints | These hash over polynomials in GF(2). Content-defined chunking cuts a file wherever the rolling hash's low bits are zero, so chunk boundaries survive insertions. Deduplicating storage such as LBFS uses this. |
Exercise
In Java, why is (hash - out * high % MOD + MOD) % MOD used instead of (hash - out * high) % MOD?
Show answer
out * high can be up to about 255·10⁹, so subtracting it makes the result negative, and Java's % keeps the sign. Reducing the product first and then adding MOD keeps the value in [0, MOD).
Exercise
Why does binary search on length work for the longest repeated substring?
Show answer
If a substring of length L occurs twice, its length-(L−1) prefix also occurs twice. So "a repeat of length L exists" is monotone in L.