Skip to content
Preptima
mediumCodingConceptMidSenior

You need to find a substring in linear time and the interviewer will not accept a library call. What do you compute, and what goes wrong on a collision?

Rabin-Karp computes a polynomial hash of the pattern and a rolling hash of each text window, updated in constant time per step modulo a large prime. Equal hashes only nominate a candidate, so you compare characters before reporting it. Skip that check and a collision is a wrong answer; keep it and collisions cost time.

5 min readUpdated 2026-10-09

Answer

Short answer

Rabin-Karp hashes instead of comparing. Compute a polynomial hash of the pattern, then a rolling hash of every pattern-length window of the text, sliding the window in O(1) by removing the leading character's term and appending the next one, all modulo a large prime. When the two hashes are equal, compare the characters before reporting a match. Expected time is O(n + m); worst case is O(nm), reached through a flood of collisions or of genuine matches, because every candidate costs a full comparison.

Was this answer helpful?

Likely follow-ups

  • Search for 5,000 different patterns that are all twelve characters long. What changes, and why is KMP worse at this?
  • Use the rolling hash to find the longest substring that appears twice. What do you binary search over?
  • You drop the verification and use two independent moduli instead. What is the error probability now, roughly?
  • The text is a stream of bytes you cannot store. Which parts of this algorithm still work?

Related questions

Related Topics