StringsAnimated
Rabin–Karp Algorithm
Compare rolling hashes of windows, verifying only on a hash match.
Time
O(n + m) avg, O(n · m) worst
Extra space
O(1)
Use it for
Searching for many patterns at once.
How it works
- Compute a number (a hash) for the pattern: treat letters as digits (a = 1 … z = 26) in base 27, modulo a prime.
- Compute the hash of each text window of the same length. Sliding by one position updates the hash in O(1): remove the leading letter, shift, add the new one.
- Only if a window hash equals the pattern hash do we compare characters (hashes can collide).
- Average O(n + m); a good fit for searching many patterns at once.
Watch it run
Loading animation…