Rabin-Karp Algorithm
Rabin-Karp Algorithm is a GFG problem (Hard). Its full name is Search Pattern (Rabin-Karp Algorithm): given a text and a pattern of lowercase letters, return every 0-based index where the pattern starts inside the text.
- Matches may overlap, and each one is reported.
- Return an empty list when the pattern never appears.
The text can hold a million letters, so checking every start letter by letter, which costs O(n · m), is too slow when the pattern is long.
- 1 <= text.length <= 10⁶
- 1 <= pattern.length <= text.length
- Both strings consist of lowercase English letters.
Intuition
Give every window of m letters a number, its hash, and compare that number with the pattern's hash. Different numbers prove the window is not the pattern, in O(1).
- Hash: read the window as a number in base 31, with
a = 1up toz = 26, kept below a large prime. - Rolling: the next window loses its first letter and gains one at the end, so remove the old letter's share, multiply by 31 and add the new letter. One window costs O(1), not O(m).
- Check: equal hashes can still come from different strings, so compare the letters before reporting a match.
When you need to find all occurrences of a pattern in a string, every window of the pattern's length has to be compared with it, and a rolling hash makes each comparison O(1). The same trick finds repeated substrings and repeated DNA sequences, where many windows have to be compared with each other.
Approach
Before reading on, write the hash of a 3-letter window as a base-31 number. Then work out how to get the next window's hash from it with one subtraction, one multiplication and one addition.
Precompute the weight of the first letter
Compute high = 31^(m-1) % MOD once. In an m-letter window, the first letter is multiplied by this weight, so it is exactly the amount to remove when that letter leaves.
Hash the pattern and the first window
Walk the first m letters of both strings, doing h = (h * 31 + value) % MOD. This is how you read digits into a number, so earlier letters end up with larger weights and the order of the letters matters.
Compare, then confirm
At each start s, compare the window hash with the pattern hash. Only when they are equal, compare the letters too, and add s to the answer if they match. Unequal hashes skip the window without reading a single letter.
Roll to the next window
Subtract value(text[s]) * high, multiply by 31, then add value(text[s + m]), reducing modulo MOD each time. The window hash now describes text[s+1 .. s+m] without rescanning it.
Keep the hash non-negative
In C++ and Java, % of a negative number stays negative, so add MOD after the subtraction. Python's % already returns a value in [0, MOD). Use 64-bit integers: MOD near 10⁹ times 31 does not fit in 32 bits.
Code in Python, C++ and Java
Common pitfalls
Letting the hash go negative in C++ or Java
th = (th - (text.charAt(s) - 'a' + 1) * high) % MOD;
th = (th - (text.charAt(s) - 'a' + 1) * high % MOD + MOD) % MOD;
Once the hash has wrapped past MOD, the subtraction can drop below zero, and Java's % keeps the minus sign. The window hash then never equals the pattern hash. With text = "baaaaaaa" and pattern = "aaaaaaa", the wrong line returns [] instead of [1].
Reporting a match on equal hashes alone
if th == ph:
res.append(s)if th == ph and text[s:s + m] == pattern:
res.append(s)A hash squeezes many strings into one number, so two different strings can share it. With the textbook choice of base 256 and modulus 101, "ah" and "ca" have the same hash, so searching "ca" would also report every "ah".
Removing the first letter with the wrong weight
high = pow(BASE, m, MOD)
high = pow(BASE, m - 1, MOD)
In an m-letter window the last letter has weight 31⁰ and the first has weight 31^(m-1). Subtracting 31^m times the first letter removes a share it never had, so every hash after the first window is wrong and matches are missed.
Edge cases
There is exactly one window, s = 0. The loop runs once and the roll is skipped because s + m < n is false.
"aa" in "aaaa"Every start is checked independently, so the answer is [0, 1, 2]. Do not jump ahead by m after a match.
Complexity
"aaa…a", those checks add up to O(n · m). The answer list is not counted.Rabin-Karp Algorithm FAQ
Why base 31 with a = 1, and not a = 0?
31 is a prime larger than the 26 letters, so different words rarely land on the same number. Starting at 1 matters when strings of different lengths are hashed, since with a = 0 the strings "b" and "ab" would both be 2. In this problem every window has the pattern's length, so the choice only keeps the code consistent with that wider use.
Can I skip the letter check to make it faster?
Only if you accept a tiny chance of a wrong answer. Many solutions keep two hashes with two different primes and trust a double match; a false match then needs a collision on both at once. With one hash and the check, the answer is always right and only the running time depends on luck.
Should I use Rabin-Karp or KMP for one pattern?
KMP and the Z-function guarantee O(n + m) even on inputs like "aaa…a", because they never re-read matched letters. Rabin-Karp is shorter to write and extends easily to comparing many substrings at once, which is why it shows up in duplicate-substring problems.