Sub topic 1
The Problem: Why Naive Substring Search Is Slow
Prerequisites
This chapter assumes you can write basic Python, index and slice strings, read Big-O notation, and use the % operator. It also assumes you know what a hash function does in general: it maps data to a number.
The Problem: Why Naive Substring Search Is Slow
Naive matching tries the pattern at every position of the text and compares it character by character. With a text of length n and a pattern of length m, there are n − m + 1 starting positions. Each one can cost up to m comparisons.
The worst case looks like this: text "aaaa…a" and pattern "aa…ab". At every position, the first m − 1 characters match and only the last one fails. That adds up to O(nm) work. The fix is to compare one number per window in place of m characters.
Modular Arithmetic You Need for Hashing
Hash values grow quickly, so we reduce them modulo a large prime such as 1,000,000,007. Two facts let us reduce at every step without changing the final result:
- (a + b) mod p = ((a mod p) + (b mod p)) mod p
- (a · b) mod p = ((a mod p) · (b mod p)) mod p
In Python, % always returns a non-negative result when the modulus is positive. That matters once subtraction appears.
Hashing a String as a Polynomial
Treat the string as the digits of a number written in base B. For the string s₀s₁…sₘ₋₁:
H = s₀·B^(m−1) + s₁·B^(m−2) + … + sₘ₋₁ (mod p)
Horner's rule computes this in a single pass:
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
print(poly_hash("abc")) # (97*256^2 + 98*256 + 99) % modSliding the Window: The Rolling Hash Update
To move the window one character to the right, do three things:
- Remove the outgoing character's term, which is
out · B^(m−1). - Shift every remaining term up one power by multiplying by B.
- Add the incoming character.
H' = ((H − out · B^(m−1)) · B + in) mod p
Precompute high = B^(m−1) mod p once. After that, each slide costs O(1) no matter how long the pattern is.
def poly_hash(s, base=256, mod=1_000_000_007):
h = 0
for ch in s:
h = (h * base + ord(ch)) % mod
return h
text, m = "abracadabra", 4
base, mod = 256, 1_000_000_007
high = pow(base, m - 1, mod)
h = poly_hash(text[:m])
for i in range(len(text) - m):
h = ((h - ord(text[i]) * high) * base + ord(text[i + m])) % mod
assert h == poly_hash(text[i + 1:i + 1 + m])
print("rolling hash matches direct hash for every window")Exercise
Use base 10, modulus 13, and each digit as its own value. The window "314" has hash 314 mod 13 = 2. Use the rolling update to get the hash of the next window, "141", and check your answer directly.
Show answer
high = 10² mod 13 = 9. The update is (2 − 3·9)·10 + 1 = −249, and −249 mod 13 = 11. Checking directly, 141 mod 13 = 11, so the two agree.