Rabin-Karp
A string search that compares hash values of the pattern and text windows. A rolling hash updates the window hash in O(1), and it only checks the actual characters when the hashes match — handy for multi-pattern search.
01Rabin-Karp
Explore How It WorksRabin-Karp starts. It compares the 'hash values' of the pattern and text windows to filter candidates fast.
Precompute the hash of pattern 'CAB' (say it's 17).
Window [0,2] 'ABA' hashes to 31. It differs from 17, so skip it without even looking at the actual chars.
A rolling hash updates the next window [1,3] 'BAC' in O(1) = 22. Still different.
Window [2,4] 'ACA' hash = 19. Different again.
Window [3,5] 'CAB' hash = 17. It matches the pattern hash! Now verify the actual chars.
The chars 'CAB' exactly equal the pattern (not a hash collision). Found at index 3!
A rolling hash updates the window hash in O(1), matching in O(n+m) on average.
02 Understand It Simply
For EveryoneCompares the hash of the pattern against the hash of each window, checking actual characters only on a match. Sliding the window updates the hash instead of recomputing it.
Compares the hash of the pattern and a text window, checking actual characters only when they match.
A rolling hash updates the window hash in O(1) to sweep fast.
- –Plagiarism/duplicate-document checks
- –multi-pattern search
03 Python Implementation
A clean, readable reference implementation of the core logic of Rabin-Karp.
04 Frequently Asked Questions
FAQWhat is Rabin-Karp?+
A string search that compares hash values of the pattern and text windows. A rolling hash updates the window hash in O(1), and it only checks the actual characters when the hashes match — handy for multi-pattern search.
What is the time complexity of Rabin-Karp?+
The time complexity of Rabin-Karp is Avg O(n + m). Follow the step-by-step visualization to see exactly why.
Where is Rabin-Karp used?+
Plagiarism/duplicate-document checks, multi-pattern search.
What's a simple analogy for Rabin-Karp?+
Compares the hash of the pattern against the hash of each window, checking actual characters only on a match. Sliding the window updates the hash instead of recomputing it.
