Home
DSA Visualizer
Strings
Rabin-Karp Algorithm
Rabin-Karp Algorithm Visualization
The Rabin-Karp algorithm searches for a pattern in a text using a rolling hash to avoid unnecessary character comparisons. Step through it in the interactive Rabin-Karp Algorithm visualization below.
PATTERN HASH 203
HASH
0
1
2
3
4
5
6
7
8
9
Pattern hash
203
Window hash
198
Matches found
Hash the pattern "CDD" once: 203. Then hash the first window "ABC": 198.
Next
Hash 198 at index 0 is not 203, so "ABC" cannot be the pattern. No characters compared.
Text
Pattern
Intuition
Comparing strings character by character is slow (O(M)). Comparing integers (hashes) is fast (O(1)). Rabin-Karp hashes the pattern and the current window. If hashes match, we double-check characters.
Concept
- Rolling Hash: Efficiently update the hash when the window slides by removing the leading character and adding the trailing one.
- Spurious Hit: When hashes match but strings don't (collision).
- Complexity: Average O(N+M), Worst case O(N*M) (many collisions).
How Rabin-Karp Algorithm Works
Algorithm:
- Calculate hash of Pattern and first window of Text.
- Loop through text:
- If
Hash(Window) == Hash(Pattern), check characters. - If match, record index.
- Update hash for next window using Rolling Hash formula.
Rabin-Karp Algorithm Visualization, Step by Step
Watch the visualization:
- See the hash value update instantly as the window moves.
- Notice that we only check characters when the hash matches (Green Box).
When to Use
- Multiple pattern search (can check multiple hashes at once).
- Plagiarism detection.
When NOT to Use
- Single pattern search where KMP is safer (no collisions).
How to Identify
"Rolling hash", "Multiple patterns", "String matching".
Practice it on interview problems
LeetCode problems solved with the Sliding Window pattern, each with a step-by-step visualizer:
Applying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
