Skip to content
Efficient

Rolling Hash

How to update a hash in O(1) as a window slides.

Time Complexity
O(1)
Space Complexity
O(1)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 14
Current Window
P
0
E
1
T
2
E
3
R
4
P
5
I
6
P
7
E
8
OperationInitial hashes computed. Pattern hash: 2, Text window hash: 68
Process Description

Initial hashes computed. Pattern hash: 2, Text window hash: 68

Technical Guide

The magic behind Rabin-Karp is the Rolling Hash. It allows us to compute the hash of the next window from the current window in O(1) time. We 'subtract' the character leaving the window and 'add' the new character entering. This is typically done using modular arithmetic and polynomial rolling hashes (e.g., base 256).

Logical Phases

  • 1
    Removing the leading character's value (Value * base^(M-1)).
  • 2
    Multiplying the remaining hash by the base.
  • 3
    Adding the new trailing character's value.
  • 4
    Applying a large prime modulus to keep numbers within register limits.

Implementation

hash = (base * (hash - charOut * h) + charIn) % prime;

Expert Pitfalls

Numeric overflow before the modulo operation is applied.