Skip to interview prep
Apexed

Explain Rabin-Karp string matching and its rolling hash.

MediumString algorithms

Technical

Content review

Report an error

Not yet reviewed

Getting your answer ready…

Show model answer

Treat each length-m window as a number in base b modulo a prime p. The hash of the next window is computed in O(1) from the previous one: subtract the leading character times b^(m−1), multiply by b, add the new character, and reduce mod p. Only when the window hash equals the pattern hash do you compare the characters, to rule out a false match.

Expected time is O(n + m); the worst case is O(nm) if many windows collide (for example, adversarial input with a fixed modulus). Its strength is matching many patterns of the same length at once (store their hashes in a set) and detecting repeated substrings, for example plagiarism detection or the longest repeated substring with binary search.

Example program

Explain Rabin-Karp string matching and its rolling hash. — Data structures & algorithms interview question — Apexed