Home
DSA Visualizer
Strings
Rabin-Karp Algorithm
Rabin-Karp Algorithm
The Rabin-Karp algorithm searches for a pattern in a text using a rolling hash to avoid unnecessary character comparisons.
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 it 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.
Step-by-Step Breakdown
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".
Applying for software engineering roles? Free, no sign-up:
