GeeksforGeeks Hard

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.

Constraints
  • 1 <= text.length <= 10⁶
  • 1 <= pattern.length <= text.length
  • Both strings consist of lowercase English letters.
stringrolling-hashpattern-matching
Open on GeeksforGeeks ↗
02

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 = 1 up to z = 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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def rabinKarp(self, text, pattern):
▶3 BASE, MOD = 31, _000_000_007
▶4 n, m = len(text), len(pattern)
▶5 high = pow(BASE, m - 1, MOD)
▶6 ph = th = 0
▶7 for i in range(m):
▶8 ph = (ph * BASE + ord(pattern[i]) - 96) % MOD
▶9 th = (th * BASE + ord(text[i]) - 96) % MOD
▶10 res = []
▶11 for s in range(n - m + 1):
▶12 if th == ph and text[s:s + m] == pattern:
▶13 res.append(s)
▶14 if s + m < n:
▶15 th = (th - (ord(text[s]) - 96) * high) % MOD
▶16 th = (th * BASE + ord(text[s + m]) - 96) % MOD
▶17 return res
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hashnot builtnot builtroll the hashnothing to roll yetmatchesnone yethash the pattern and the first 4 letters
m4pattern length
first letter weight31³= 29791
Letters become numbers, a = 1 up to z = 26, and a 4-letter string is read as a number in base 31. The first letter of a window carries weight 31³ = 29791, which is exactly what has to be removed when it leaves.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash213508213508roll the hashwindow 0 is hashed letter by lettermatchesnone yetpattern hash 213508, window 0 hash 213508
pattern hash213508'geek'
window hash213508'geek'
Both hashes are built the way digits are read into a number: multiply by 31, add the next letter. The pattern hash never changes from here on. Only the window hash moves, and only by a roll.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash213508213508=roll the hashwindow 0 is hashed letter by lettermatchesnone yetwindow 0: hashes equal → check the letters
s0window 'geek'
window hash213508
pattern hash213508
The window hash equals the pattern hash, so 'geek' might be the pattern. Equal hashes are only a hint, so the letters get compared next.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash213508213508=roll the hashwindow 0 is hashed letter by lettermatches0letters match → record 0
lettersequal
res[0]
Every letter of 'geek' matches the pattern, so index 0 is a real start. The search does not jump ahead: the next window starts one letter later, so overlapping matches are still found.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash154120213508≠roll the hash− 7 × 31³× 31+ 19drop 7, add 19matches0window 1: hashes differ → skip
s1window 'eeks'
window hash154120rolled in O(1)
pattern hash213508
Roll: remove 'g' 7 times 31³, multiply by 31, add 's' 19. The hashes differ, so 'eeks' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash160121213508≠roll the hash− 5 × 31³× 31+ 6drop 5, add 6matches0window 2: hashes differ → skip
s2window 'eksf'
window hash160121rolled in O(1)
pattern hash213508
Roll: remove 'e' 5 times 31³, multiply by 31, add 'f' 6. The hashes differ, so 'eksf' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash346161213508≠roll the hash− 5 × 31³× 31+ 15drop 5, add 15matches0window 3: hashes differ → skip
s3window 'ksfo'
window hash346161rolled in O(1)
pattern hash213508
Roll: remove 'e' 5 times 31³, multiply by 31, add 'o' 15. The hashes differ, so 'ksfo' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash572278213508≠roll the hash− 11 × 31³× 31+ 18drop 11, add 18matches0window 4: hashes differ → skip
s4window 'sfor'
window hash572278rolled in O(1)
pattern hash213508
Roll: remove 'k' 11 times 31³, multiply by 31, add 'r' 18. The hashes differ, so 'sfor' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash193726213508≠roll the hash− 19 × 31³× 31+ 7drop 19, add 7matches0window 5: hashes differ → skip
s5window 'forg'
window hash193726rolled in O(1)
pattern hash213508
Roll: remove 's' 19 times 31³, multiply by 31, add 'g' 7. The hashes differ, so 'forg' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash464385213508≠roll the hash− 6 × 31³× 31+ 5drop 6, add 5matches0window 6: hashes differ → skip
s6window 'orge'
window hash464385rolled in O(1)
pattern hash213508
Roll: remove 'f' 6 times 31³, multiply by 31, add 'e' 5. The hashes differ, so 'orge' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash543125213508≠roll the hash− 15 × 31³× 31+ 5drop 15, add 5matches0window 7: hashes differ → skip
s7window 'rgee'
window hash543125rolled in O(1)
pattern hash213508
Roll: remove 'o' 15 times 31³, multiply by 31, add 'e' 5. The hashes differ, so 'rgee' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash213508213508=roll the hash− 18 × 31³× 31+ 11drop 18, add 11matches0window 8: hashes equal → check the letters
s8window 'geek'
window hash213508rolled in O(1)
pattern hash213508
Roll: remove 'r' 18 times 31³, multiply by 31, add 'k' 11. The window hash equals the pattern hash, so 'geek' might be the pattern. Equal hashes are only a hint, so the letters get compared next.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash213508213508=roll the hash− 18 × 31³× 31+ 11drop 18, add 11matches08letters match → record 8
lettersequal
res[0, 8]
Every letter of 'geek' matches the pattern, so index 8 is a real start. The search does not jump ahead: the next window starts one letter later, so overlapping matches are still found.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash154120213508≠roll the hash− 7 × 31³× 31+ 19drop 7, add 19matches08window 9: hashes differ → skip
s9window 'eeks'
window hash154120rolled in O(1)
pattern hash213508
Roll: remove 'g' 7 times 31³, multiply by 31, add 's' 19. The hashes differ, so 'eeks' cannot be the pattern. Different strings may share a hash, but equal strings always share one, so a different hash is proof. No letter is read.
textg0e1e2k3s4f5o6r7g8e9e10k11s12patterngeekwindow hashpattern hash154120213508roll the hashend of the textmatches08answer: 0, 8
result[0, 8]
Every one of the 10 windows was tested with one number comparison, and letters were read only for the 2 real matches. The answer is [0, 8].
05

Common pitfalls

Letting the hash go negative in C++ or Java

✗ Wrong
th = (th - (text.charAt(s) - 'a' + 1) * high) % MOD;
✓ Right
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

✗ Wrong
if th == ph:
    res.append(s)
✓ Right
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

✗ Wrong
high = pow(BASE, m, MOD)
✓ Right
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.

06

Edge cases

Pattern as long as the text

There is exactly one window, s = 0. The loop runs once and the roll is skipped because s + m < n is false.

Overlapping matches, such as "aa" in "aaaa"

Every start is checked independently, so the answer is [0, 1, 2]. Do not jump ahead by m after a match.

07

Complexity

Time
O(n + m) expected
Space
O(1) extra
Hashing the first window and the pattern costs O(m), and each roll is O(1). Each letter check costs O(m), but with a modulus near 10⁹ almost every check is a real match. When there are very many overlapping real matches, as in "aaa…a", those checks add up to O(n · m). The answer list is not counted.
08

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.