Skip to content
StackDecode
StringsAnimated

Rolling Hash

Update a window hash by removing the old character and adding the new one.

Time

O(1) per slide

Extra space

O(1)

Use it for

Duplicate detection, Rabin–Karp.

How it works

  1. Give each letter a number (a = 1, b = 2, …) and read a window as a number in base 27.
  2. Instead of recomputing from scratch for each window, update: subtract the leading letter’s contribution, multiply by the base, add the new letter.
  3. Each slide costs O(1), no matter how long the window is.
  4. This is the engine inside Rabin–Karp and many duplicate-detection tools.

Watch it run

Loading animation…