Skip to content
StackDecode
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

  1. Compute a number (a hash) for the pattern: treat letters as digits (a = 1 … z = 26) in base 27, modulo a prime.
  2. 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.
  3. Only if a window hash equals the pattern hash do we compare characters (hashes can collide).
  4. Average O(n + m); a good fit for searching many patterns at once.

Watch it run

Loading animation…