Home
DSA Course
Strings
Rabin-Karp Algorithm
Rabin-Karp Algorithm
Visualize pattern searching using Rolling Hash to avoid unnecessary character comparisons.
Pattern Hash
-
Window Hash
-
Ready to search with Rabin-Karp.
A
65B
66C
67C
67D
68D
68A
65E
69F
70G
71See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
