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
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
- 1Removing the leading character's value (Value * base^(M-1)).
- 2Multiplying the remaining hash by the base.
- 3Adding the new trailing character's value.
- 4Applying 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.