Rabin-Karp String Matching
Rolling hashes for constant-time window screening
Compare fingerprints before characters
Rabin-Karp hashes the pattern and each text window of the same length. Unequal hashes prove the strings differ, so the window can be skipped immediately. Equal hashes are only a candidate match because different strings can collide.
Roll the hash as the window moves
A polynomial rolling hash removes the outgoing character's weighted contribution, shifts the remaining value by the base, and adds the incoming character. This updates the next window in O(1) time instead of hashing all m characters again.
The player scans abcabcab for cab. It displays the current window and both hashes. Hash equality triggers a character verification; successful verification records the starting index in green.
Hash pattern "cab" to 312, then begin with the first text window.
Expected linear time with a worst-case caveat
Initial hashes cost O(m) and the scan performs O(n) rolling updates. With rare collisions, expected time is O(n + m). Repeated collisions can force O(nm) character verification, so robust implementations use large moduli, randomized bases, or double hashing.
Compare hash-based screening with prefix reuse in KMP String Matching, then explore palindrome symmetry in Manacher's algorithm.