What is the Rabin-Karp Algorithm?
Rabin-Karp searches for a pattern inside a text by comparing hash values instead of raw characters. It computes a hash for the pattern once, then slides a same-sized window across the text, updating the window's hash in constant time using a "rolling hash" - dropping the outgoing character's contribution and adding the incoming one.
Because different strings can occasionally share the same hash (a collision), a hash match only means "probably equal" - the algorithm always double-checks with a direct character comparison before reporting a real match. This trade-off makes Rabin-Karp especially well suited to searching for multiple patterns at once, unlike KMP or Boyer-Moore, which are tuned for a single pattern.
Time & Space Complexity
- Average CaseO(n + m)
- Worst CaseO(n · m)
- SpaceO(1)
* Worst case occurs when many spurious hits force repeated full comparisons - a large modulus makes this rare in practice.
Real-World Use Cases
- ✓Plagiarism DetectionHashing overlapping chunks of text to find duplicated passages quickly.
- ✓Multiple Pattern SearchSearching for many patterns at once by hashing them into a set.
- ✓DNA Sequence SearchLocating short subsequences within long genomic strings.