Algorithms · Visualized
String: Rabin-Karp
String Matching
Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.
Rabin-Karp searches for a pattern by comparing hash values instead of raw characters. Time: O(n + m) average, O(n × m) — rare, occurs with many hash collisions worst; space: O(1).
Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.
Rabin-Karp
String MatchingRabin-Karp searches for a pattern by comparing hash values instead of raw characters. It computes a hash of the pattern and a 'rolling hash' of each window of text (updating it in O(1) as the window slides), only doing a full character-by-character check when the hashes match, to rule out hash collisions.
How Rabin-Karp Works
- Compute a hash value for the pattern.
- Compute a hash value for the first window of text (same length as the pattern).
- Compare the text window's hash with the pattern's hash; if they match, do a full character comparison to confirm (avoiding false positives from hash collisions).
- Slide the window forward by one character, updating the hash efficiently using a 'rolling hash' formula (remove the leftmost character's contribution, add the new rightmost character's contribution) — without rehashing the whole window from scratch.
- Repeat comparing hashes and confirming matches until the window reaches the end of the text.
Rabin-Karp Worked Example
Input: {text: GEEKS FOR GEEKS, pattern: GEEK}
Hash of 'GEEK' is computed once. Hash of text window 'GEEK' (0-3) matches → confirm character by character → match at index 0. Slide window, roll the hash forward efficiently for each new window, checking for matches. A second full match of 'GEEK' is found starting at index 10.
def rabin_karp(text, pat):
m, n = len(pat), len(text)
if m > n:
return []
mod = 10**9 + 7
base = 256
hp = 0
hw = 0
power = 1
for i in range(m):
hp = (hp * base + ord(pat[i])) % mod
hw = (hw * base + ord(text[i])) % mod
power = power * base % mod
out = []
for i in range(n - m + 1):
if hp == hw and text[i:i + m] == pat:
out.append(i)
if i < n - m:
hw = (hw * base - ord(text[i]) * power + ord(text[i + m])) % mod
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Rabin-Karp Time & Space Complexity
When to Use Rabin-Karp
- Plagiarism detection systems, comparing many document fingerprints (hashes) quickly.
- Searching for multiple patterns simultaneously, since hashes for different patterns can be checked together efficiently.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.