Sub topic 2
Modular Arithmetic You Need for Hashing
A rolling hash turns a string into one integer and then updates that integer as a window slides along the text. If you never limited the size of that integer, a hash of a 1,000-character window would have thousands of digits. Arithmetic on numbers that large is slow, and in Java or C++ it overflows silently. Modular arithmetic fixes this. You keep only the remainder after division by a fixed number, so every value stays small, and the algebra the hash relies on still holds.
This chapter assumes you can write loops and functions in Python, know what the % operator does on positive integers, and are comfortable with Big-O notation. It covers the rules you will use in every later chapter: which operations survive reduction, how negative numbers behave, how to raise a number to a power under a modulus, and why the modulus should be a large prime.
Remainders and Congruence
For a positive integer m (the modulus), a mod m is the remainder r with 0 <= r < m such that a = q*m + r for some integer q. Two integers are congruent modulo m, written a ≡ b (mod m), when they have the same remainder. Equivalently, m divides a - b.
Think of a clock with m positions. Adding moves you around the clock, and the remainder is where you land. A hash under modulus m is always one of the m positions 0, 1, ..., m-1.
The Three Operations That Survive Reduction
The property that makes hashing practical is this: for addition, subtraction, and multiplication, you get the same final remainder whether you reduce at the end or at every intermediate step.
(a + b) mod m = ((a mod m) + (b mod m)) mod m(a - b) mod m = ((a mod m) - (b mod m)) mod m(a * b) mod m = ((a mod m) * (b mod m)) mod m
These hold because replacing a with a mod m changes it by a multiple of m, and adding, subtracting, or multiplying by a multiple of m does not change the remainder.
MOD = 1_000_000_007
a, b = 123_456_789_012, 987_654_321_098
print((a + b) % MOD == ((a % MOD) + (b % MOD)) % MOD) # True
print((a - b) % MOD == ((a % MOD) - (b % MOD)) % MOD) # True
print((a * b) % MOD == ((a % MOD) * (b % MOD)) % MOD) # TrueDivision does not follow this rule. (12 / 4) mod 5 is 3. But 12 mod 5 = 2 and 4 mod 5 = 4, and 2 / 4 is not even an integer. Dividing under a modulus requires a modular inverse, which is covered below.
| Operation | Safe to reduce at every step? | Notes |
|---|---|---|
| Addition | Yes | Result is below `2m` before the final reduction |
| Subtraction | Yes | Intermediate result may be negative; see next section |
| Multiplication | Yes | Product of two residues is below `m²`; check it fits your integer type |
| Exponentiation | Yes | Use repeated squaring, reducing after each multiply |
| Division | No | Multiply by a modular inverse instead |
The polynomial hash in the next chapter is built from repeated "multiply by the base, add a character, reduce" steps. Because multiplication and addition survive reduction, the reduced value is exactly the remainder of the full, enormous polynomial.
Negative Remainders
Subtraction appears in the rolling update, where you remove the outgoing character's contribution. The difference can be negative, and languages disagree about what % returns for a negative left operand.
| Expression | Python | Java, C, C++, JavaScript |
|---|---|---|
| `-7 % 5` | `3` | `-2` |
| `7 % 5` | `2` | `2` |
Python's % takes the sign of the divisor, so with a positive modulus the result is always in [0, m). Java, C, C++, and JavaScript truncate toward zero, so the result takes the sign of the dividend. A negative hash value will never equal the pattern's non-negative hash, and Rabin-Karp will silently miss matches.
The portable fix is to add m before the final reduction:
def norm(x, m):
"""Return x mod m in [0, m), using only truncating-style steps."""
return ((x % m) + m) % m
print(norm(-7, 5), norm(7, 5)) # 3 2In Python this is redundant, but writing it this way makes the code safe to port. A later chapter covers the fixed-width details for Java and C++.
How Big Can Intermediate Values Get?
When both operands are already reduced, they are below m, so their product is below m². With m = 1_000_000_007, m² is about 1.0 × 10^18. A signed 64-bit integer holds values up to about 9.22 × 10^18, so the product fits. This is the main reason 10^9 + 7 is such a common modulus. It is prime, it is large, and the product of two residues fits in a long.
Python integers have arbitrary precision, so they never overflow. They do get slower as they grow, though, so reducing at each step still matters for speed.
Modular Exponentiation
The rolling update needs base^(m-1) mod mod, the weight of the leading character in a window of length m. Computing base**(m-1) in full and then reducing works, but for long windows that number is enormous. Square-and-multiply computes the power in O(log exp) multiplications and keeps every intermediate value reduced:
def mod_pow(base, exp, mod):
result = 1
base %= mod
while exp > 0:
if exp & 1:
result = result * base % mod
base = base * base % mod
exp >>= 1
return result
print(mod_pow(256, 9, 1_000_000_007))
print(mod_pow(256, 9, 1_000_000_007) == pow(256, 9, 1_000_000_007)) # TrueIn Python, use the built-in three-argument pow(base, exp, mod), which does the same thing in C. In a Rabin-Karp search you compute this power once, before the scan, so even a simple loop of m - 1 multiplications is acceptable.
Modular Inverses
When the modulus p is prime and a is not a multiple of p, there is a unique x in [1, p) with a * x ≡ 1 (mod p). This x is the modular inverse of a, and multiplying by it acts as division. By Fermat's little theorem, x = a^(p-2) mod p. Python 3.8 and later also accept pow(a, -1, p).
p = 1_000_000_007
inv = pow(256, p - 2, p)
print(256 * inv % p) # 1
print(inv == pow(256, -1, p)) # TrueThe code in this tutorial avoids division: the rolling update and the prefix-hash formula both subtract a multiplied term instead. Inverses still help you read other implementations, and they explain why prime moduli behave well. If the modulus is composite and shares a factor with the base, the base has no inverse, and information gets lost.
Why the Modulus Should Be a Large Prime
Here is the failure in its most extreme form. With base 256 and modulus 256, the base is congruent to 0. Each step multiplies the previous hash by zero, so the final hash is just the code of the last character:
def h(s, base, mod):
v = 0
for ch in s:
v = (v * base + ord(ch)) % mod
return v
print(h("xyzA", 256, 256), h("qrsA", 256, 256)) # 65 65
print(h("xyzA", 256, 1_000_000_007) == h("qrsA", 256, 1_000_000_007)) # FalseA milder version of this happens with modulus 2^64 (the natural wraparound of unsigned 64-bit integers) and an even base. Each multiplication by the base shifts the earlier characters toward the high bits, and after 64 characters they have been pushed out completely. A prime modulus has no factors in common with any base smaller than it, so multiplying by the base is a one-to-one mapping and no character's contribution disappears.
Size matters too. The hash takes at most m distinct values, so a modulus of 101 guarantees frequent collisions on any real text. With a modulus near 10^9, two different random strings collide with probability about 1/m, roughly one in a billion. The chapter on choosing parameters looks at how base, modulus, and randomization together control collisions.
Exercises
Exercise
Without running code, compute 256^3 mod 1000 by reducing after each multiplication.
Show answer
256^2 = 65536, and 65536 mod 1000 = 536. Then 536 * 256 = 137216, and 137216 mod 1000 = 216. So 256^3 mod 1000 = 216, the same as the last three digits of 16777216.
Exercise
A Java implementation computes (hash - out * high) % MOD and sometimes misses matches that the Python version finds. Explain the cause and give a one-line fix.
Show answer
In Java, % on a negative left operand returns a negative result, so the window hash can be negative and never equals the non-negative pattern hash. Normalize it: ((hash - out * high % MOD) % MOD + MOD) % MOD. Reducing out * high first also keeps the product within range.
Exercise
Why does using modulus 2^32 with base 256 make the hash of any string of length 4 or more depend only on its last 4 characters?
Show answer
256 = 2^8, so after k more steps a character's contribution has been multiplied by 2^(8k). Once 8k >= 32, that contribution is a multiple of 2^32 and reduces to 0. Only the last 4 characters survive, so any two strings that end in the same 4 characters collide.