Sub topic 9
Avoiding Overflow and Negative Remainders in Java and C++
The Python versions of Rabin-Karp in earlier chapters never had to think about integer size. Python integers grow as large as needed, and Python's % always returns a result with the same sign as the divisor. Java and C++ give you neither guarantee. This chapter covers the two bugs that appear when you port a rolling hash to a fixed-width language, silent overflow and negative remainders, and shows how to avoid both.
This chapter assumes you have read the chapters on polynomial hashing and the rolling update, you can read basic Java or C++, and you know that a 64-bit signed integer holds values up to about 9.22 × 10^18.
Two Failure Modes
Overflow
A fixed-width integer has a maximum value. In Java, int is 32 bits (max 2,147,483,647) and long is 64 bits (max 9,223,372,036,854,775,807). When a result goes past the limit:
- Java wraps it around silently. The program keeps running with a wrong hash.
- C++ treats signed overflow as undefined behavior. The compiler may assume it never happens and optimize on that basis, so you can get wrong answers, inconsistent answers, or answers that change with the optimization level.
The overflow happens in the multiplications. With MOD = 1_000_000_007, a hash value can be close to 10^9. Multiplying it by BASE = 256 gives about 2.56 × 10^11, which is far beyond int and fine for long.
Negative remainders
Java and C++ (since C++11) define integer division as truncating toward zero, so the remainder takes the sign of the dividend:
| Expression | Python | Java | C++ |
|---|---|---|---|
| `-3 % 7` | `4` | `-3` | `-3` |
| `10 % 7` | `3` | `3` | `3` |
| `-14 % 7` | `0` | `0` | `0` |
The rolling update subtracts the outgoing character's contribution, hash - out * high. That difference is often negative. In Java or C++, a negative difference stays negative after % MOD. The window hash then fails to equal the pattern hash even when the window and pattern are identical, and Rabin-Karp silently misses real matches.
Bounding Every Intermediate Value
The reliable way to avoid overflow is to bound each intermediate value and check it against the type's limit. Assume every stored hash is already reduced, so 0 ≤ hash < MOD.
| Quantity | Upper bound (MOD = 10^9+7, BASE = 256) | Fits in `int`? | Fits in `long` / `int64_t`? |
|---|---|---|---|
| `hash` | about 1.0 × 10^9 | yes | yes |
| `hash * BASE + c` (c ≤ 65535) | about 2.6 × 10^11 | no | yes |
| `out * high` (Java `char`, out ≤ 65535) | about 6.6 × 10^13 | no | yes |
| `hash * hash` (when the base itself is a residue up to MOD) | about 1.0 × 10^18 | no | yes, under 9.22 × 10^18 |
| `hash * hash` with MOD near 4 × 10^9 | about 1.6 × 10^19 | no | **no** |
The last two rows show the general rule. If you multiply two residues, MOD squared must fit in the type. For signed 64-bit, MOD must be below about 3.03 × 10^9. That is why 10^9 + 7 and 998244353 are popular choices: they leave room for a randomly chosen base anywhere in [2, MOD), which the chapter on parameter choice recommends.
The Safe Rolling Update
The rolling update from the Topic Spine, in Java:
static final long MOD = 1_000_000_007L;
static final long BASE = 256L;
// hash: hash of text[i .. i+m-1]; high: BASE^(m-1) % MOD
static long roll(long hash, char outgoing, char incoming, long high) {
long next = (hash - (long) outgoing * high % MOD + MOD) % MOD;
return (next * BASE + incoming) % MOD;
}Here is why each piece is needed.
(long) outgoing * high % MOD: the cast binds before*, and*and%evaluate left to right, so this means((long) outgoing * high) % MOD. The result lies in[0, MOD).hash - that: both terms lie in[0, MOD), so the difference lies in(-MOD, MOD).+ MOD: shifts the range to(0, 2·MOD). The value is now strictly positive.% MOD: brings it back into[0, MOD). Because the operand is positive, Java's%behaves like the mathematical one.next * BASE + incoming: at most about 2.6 × 10^11, safe inlong, then reduced.
Adding MOD once is enough only because step 1 reduced the subtrahend first. If you write hash - outgoing * high + MOD without reducing, the difference can be as low as about −6.6 × 10^13, and adding one MOD does not make it positive.
When you have a value of unknown sign and no bound on it, use a general normalizer. In Java, Math.floorMod(x, MOD) returns the Python-style result. In C++, write ((x % MOD) + MOD) % MOD.
A Complete Java Implementation
import java.util.ArrayList;
import java.util.List;
public class RabinKarp {
static final long MOD = 1_000_000_007L;
static final long BASE = 256L;
static long roll(long hash, char outgoing, char incoming, long high) {
long next = (hash - (long) outgoing * high % MOD + MOD) % MOD;
return (next * BASE + incoming) % MOD;
}
static List<Integer> search(String text, String pattern) {
int n = text.length(), m = pattern.length();
List<Integer> matches = new ArrayList<>();
if (m == 0) {
for (int i = 0; i <= n; i++) matches.add(i);
return matches;
}
if (m > n) return matches;
long high = 1;
for (int i = 0; i < m - 1; i++) high = high * BASE % MOD;
long p = 0, t = 0;
for (int i = 0; i < m; i++) {
p = (p * BASE + pattern.charAt(i)) % MOD;
t = (t * BASE + text.charAt(i)) % MOD;
}
for (int i = 0; i + m <= n; i++) {
if (p == t && text.regionMatches(i, pattern, 0, m)) matches.add(i);
if (i + m < n) t = roll(t, text.charAt(i), text.charAt(i + m), high);
}
return matches;
}
public static void main(String[] args) {
System.out.println(-3 % 7); // -3
System.out.println(Math.floorMod(-3, 7)); // 4
System.out.println(search("abracadabra", "abra")); // [0, 7]
}
}Every hash variable is long. Java's char is an unsigned 16-bit value, so pattern.charAt(i) is never negative and widens to long automatically when it is added to p * BASE.
A Complete C++ Implementation
C++ adds a gotcha that Java does not have. Plain char is signed on most x86 compilers, so bytes 128–255 (for example, UTF-8 continuation bytes) read as negative numbers. Cast each character to unsigned char before using it in a hash.
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
const int64_t MOD = 1000000007LL;
const int64_t BASE = 256;
int64_t code(char c) { return static_cast<unsigned char>(c); }
std::vector<int> rabin_karp(const std::string& text, const std::string& pattern) {
const int n = static_cast<int>(text.size());
const int m = static_cast<int>(pattern.size());
std::vector<int> matches;
if (m == 0) {
for (int i = 0; i <= n; ++i) matches.push_back(i);
return matches;
}
if (m > n) return matches;
int64_t high = 1;
for (int i = 0; i < m - 1; ++i) high = high * BASE % MOD;
int64_t p = 0, t = 0;
for (int i = 0; i < m; ++i) {
p = (p * BASE + code(pattern[i])) % MOD;
t = (t * BASE + code(text[i])) % MOD;
}
for (int i = 0; i + m <= n; ++i) {
if (p == t && text.compare(i, m, pattern) == 0) matches.push_back(i);
if (i + m < n) {
t = (t - code(text[i]) * high % MOD + MOD) % MOD;
t = (t * BASE + code(text[i + m])) % MOD;
}
}
return matches;
}
int main() {
std::cout << (-3 % 7) << '\n'; // -3
for (int pos : rabin_karp("abracadabra", "abra")) std::cout << pos << ' ';
std::cout << '\n'; // 0 7
}Common Mistakes
- Multiplying two
ints and storing the product in along.long x = a * b;withint a, boverflows before the assignment widens it. Declare the operands aslong, or cast one of them:(long) a * b. - Writing
1e9 + 7in C++. That is adouble, and using it with%is a compile error. If you assign it to an integer first, it works, but only by accident. Write1000000007LL. - Reducing only at the end.
(hash * BASE + c)repeated across a long string without% MODat every step overflows within a few characters. - Forgetting that
highmust be reduced too. ComputeBASE^(m-1)with repeated multiply-and-reduce, never withMath.pow, which returns adoubleand loses precision.
Going Past 64 Bits
Sometimes you want a modulus near 2^61 so that collisions become very rare. The product of two residues then needs up to 122 bits. GCC and Clang provide __uint128_t for this, and the Mersenne prime 2^61 − 1 allows a fast reduction without division:
#include <cstdint>
#include <iostream>
const uint64_t M61 = (1ULL << 61) - 1;
uint64_t mulmod61(uint64_t a, uint64_t b) {
__uint128_t x = static_cast<__uint128_t>(a) * b;
uint64_t r = static_cast<uint64_t>(x & M61) + static_cast<uint64_t>(x >> 61);
if (r >= M61) r -= M61;
return r;
}
int main() {
std::cout << mulmod61(M61 - 1, M61 - 1) << '\n'; // (-1)*(-1) = 1
}The reduction works because 2^61 ≡ 1 (mod 2^61 − 1), so the high bits can be added to the low bits. Java has no 128-bit type. Math.multiplyHigh (Java 9 and later) returns the upper 64 bits of a product, and you can build the same reduction from it. Most Java code uses double hashing with two moduli near 10^9 instead.
Exercise
A Java programmer writes int h = 0; for (char c : s.toCharArray()) h = (h * 256 + c) % 1_000_000_007;. Explain what goes wrong and give the fix.
Show answer
h can reach about 10^9, so h * 256 (about 2.56 × 10^11) overflows int, which tops out at about 2.1 × 10^9. Java wraps silently, so the hash is wrong and can even be negative. Declare h as long (and use a long constant such as 1_000_000_007L) so the product is computed in 64 bits.
Exercise
In the expression (hash - out * high % MOD + MOD) % MOD, suppose you remove the inner % MOD and write (hash - out * high + MOD) % MOD. With MOD = 10^9+7, out = 200, and high = 5 × 10^8, what does Java compute for hash = 3, and why is it wrong?
Show answer
out * high is 10^11, so the operand is 3 − 10^11 + 1,000,000,007 = −98,999,999,990. Java's % keeps the sign of the dividend and returns a negative value (−998,999,297) instead of the correct residue 1,000,710. A single + MOD only fixes differences greater than −MOD, which requires reducing the subtracted term first.
Exercise
You want to pick a random base in [2, MOD) and store hashes in a signed 64-bit long. Is MOD = 4,294,967,291 (a prime just below 2^32) safe? What is the largest safe MOD, roughly?
Show answer
No. Multiplying two residues can produce about (4.29 × 10^9)^2 ≈ 1.8 × 10^19, which exceeds the signed 64-bit maximum of about 9.22 × 10^18. MOD squared must stay below 2^63, so MOD must be under about 3.03 × 10^9. Primes such as 10^9+7 or 2,147,483,647 are safe.