Rolling hash and Rabin-Karp
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Instead of comparing strings character by character, we can convert each substring into a numerical hash. We start with naive substring hashing to see why recalculating hashes is slow, and then roll the hash in constant time.
Brute Force Substring Hashing and Its Bottleneck
A rolling hash updates the hash of a sliding text window in O(1) when one character leaves and another enters, so a pattern can be searched quickly.
A naive substring hash computes the numerical value of each M-character window from scratch, so substrings can be compared using numbers instead of characters.
int n = text.length();for (int i = 0; i + m <= n; i++) { long h = 0; for (int k = i; k < i + m; k++) { h = h * BASE + text.charAt(k); // rebuilds the whole window: O(M) per window } // compare h with the pattern's hash ...}Why does this fail to improve search speed? If you recompute the hash function for every window of length M, computing one hash requires O(M) character operations. Across N - M + 1 windows, total runtime is still O(N * M)!
Notice the redundancy: when sliding a window from index i to i + 1, exactly one character leaves the left edge and one character enters the right edge. The remaining M - 2 characters in the middle are identical.
The Polynomial Rolling Hash Formula
A polynomial rolling hash treats characters as digits in a base-B numbering system, taken modulo a large prime P: H = (c[0]B^(M-1) + c[1]B^(M-2) + ... + c[M-1]) % P.
Example 1 · Pattern search by comparing substrings, brute force: O(N · M) time, O(M) space
import java.util.ArrayList;import java.util.List;
public class SubstringCompareDemo { static List<Integer> search(String text, String pattern) { List<Integer> matches = new ArrayList<>(); int m = pattern.length(); for (int i = 0; i + m <= text.length(); i++) { if (text.substring(i, i + m).equals(pattern)) { // compares up to M characters matches.add(i); } } return matches; }
public static void main(String[] args) { String text = "abracadabra"; String pattern = "abra"; System.out.println("Matches: " + search(text, pattern)); }}Matches: [0, 7]
What this code does
- substring() copies M letters and equals() may compare all M of them, for each of the N windows.
- It finds matches at 0 and 7, the same as Rabin-Karp.
- Rolling hashes replace the copy and comparison with one number check per window.
Example 2 · Rabin-Karp search, optimal: O(N + M) expected time, O(1) extra space
import java.util.ArrayList;import java.util.List;
public class RabinKarpDemo { private static final int BASE = 31; private static final int MOD = 1_000_000_007;
public static List<Integer> search(String text, String pattern) { List<Integer> matches = new ArrayList<>(); int n = text.length(), m = pattern.length(); if (m > n) return matches;
long patternHash = 0, textHash = 0, power = 1; for (int i = 0; i < m; i++) { patternHash = (patternHash * BASE + pattern.charAt(i)) % MOD; textHash = (textHash * BASE + text.charAt(i)) % MOD; if (i > 0) power = (power * BASE) % MOD; }
for (int i = 0; i <= n - m; i++) { if (patternHash == textHash) { // Verify to rule out collision if (text.substring(i, i + m).equals(pattern)) { matches.add(i); } } if (i < n - m) { textHash = (textHash - (text.charAt(i) * power) % MOD + MOD) % MOD; textHash = (textHash * BASE + text.charAt(i + m)) % MOD; } } return matches; }
public static void main(String[] args) { String text = "abracadabra"; String pattern = "abra"; System.out.println("Matches: " + search(text, pattern)); }}Matches: [0, 7]
What this code does
- Precomputes power = BASE^(m-1) % MOD to remove outgoing characters in O(1).
- Rolls the hash across all windows in strictly O(N) arithmetic operations.
- Finds 'abra' at indices 0 and 7, verifying matching hashes against false collisions.
- Why faster: each window hash is rolled from the previous one in O(1), and letters are compared only when the hashes match.
Example 3 · Rolling the window one step: O(1) per window
public class RollingHashStepDemo { public static void main(String[] args) { int base = 10, mod = 1000; // String "1234": windows "123" -> "234" int h1 = (1 * 100 + 2 * 10 + 3) % mod; // 123 // Roll: remove 1*100, multiply by 10, add 4 int h2 = ((h1 - 1 * 100) * base + 4) % mod; System.out.println("Window 1 hash: " + h1); System.out.println("Window 2 hash: " + h2); }}Window 1 hash: 123 Window 2 hash: 234
What this code does
- Window '123' has base-10 value 123.
- Subtracting 1*100 gives 23. Multiplying by 10 gives 230. Adding 4 gives 234.
- Illustrates why window updates take constant O(1) arithmetic.
To slide the window one position to the right, we perform three fast arithmetic steps: 1) subtract the outgoing left character's contribution c[0]*B^(M-1), 2) multiply the entire remaining hash by base B to shift all positional powers up by one, and 3) add the new incoming right character c[M]. All three operations are basic modular arithmetic taking O(1) time. The entire text of length N can be scanned in O(N) time after an initial O(M) pattern hash computation.
Predict the output
Predict the hash
This uses base 10 so the numbers stay easy to read.
Round 1 of 3
Managing Collisions with Double Hashing
Because we map an infinite number of possible strings to a finite set of integers [0, P - 1], two different strings can produce the exact same hash value. This is called a hash collision or a spurious hit.
Example 4 · Double hashing: still O(N + M), far fewer collisions
public class DoubleHashDemo { private static final int BASE = 31; private static final int MOD1 = 1_000_000_007; private static final int MOD2 = 1_000_000_009;
public static long[] computeHash(String s) { long h1 = 0, h2 = 0; for (int i = 0; i < s.length(); i++) { h1 = (h1 * BASE + s.charAt(i)) % MOD1; h2 = (h2 * BASE + s.charAt(i)) % MOD2; } return new long[]{h1, h2}; }
public static void main(String[] args) { long[] h = computeHash("algorithm"); System.out.println("Hash 1: " + h[0]); System.out.println("Hash 2: " + h[1]); }}Hash 1: 491594355 Hash 2: 491422763
What this code does
- Computes two hash values simultaneously using distinct modulo primes.
- A collision occurs only if both hashes match simultaneously.
- Reduces collision chance to roughly 1 in 10^18.
When Rabin-Karp finds matching hashes, we verify the actual characters character-by-character. If they match, a true occurrence is confirmed. If they differ, the match was a false positive. In competitive programming where adversarial inputs are designed to trigger collisions, we use double hashing: computing two independent hashes with different bases and prime moduli (e.g. P1 = 10^9 + 7, P2 = 10^9 + 9). The odds of a simultaneous collision drop to approximately 1 in 10^18.
Applications: Longest Duplicate Substrings and Plagiarism
The longest duplicate substring is the longest substring that appears at least twice; to find it, combine binary search with rolling hashes. The same idea powers plagiarism checkers, file deduplication, and bioinformatics tools that must compare huge volumes of text efficiently.
int lo = 1, hi = s.length() - 1, best = 0;while (lo <= hi) { int len = (lo + hi) / 2; if (hasDuplicate(s, len)) { // rolling hashes of every len-window in a HashSet: O(N) best = len; // a duplicate exists: try longer lo = len + 1; } else { hi = len - 1; // none: try shorter }}For a candidate length L, we compute rolling hashes for all L-length windows in O(N) time and insert them into a hash set.
If any hash appears twice (and matches upon verification), a duplicate of length L exists. Testing lengths with binary search finds the maximum duplicate substring length in O(N log N) total time.
Next step
Check your understanding
10 quick questions