Skip to content
Preptima
hardCodingConceptMidSeniorStaff

Find every occurrence of a pattern in a text without ever moving backwards through the text. What does your precomputed table hold?

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Precompute, for each prefix of the pattern, the length of the longest proper prefix of the pattern that is also a suffix of that prefix.On a mismatch you fall back to that length instead of rewinding the text, which is what turns the quadratic naive scan into a linear one.

Was this answer helpful?

Likely follow-ups

  • Search for a whole set of patterns at once. What structure replaces the single table?
  • Rabin-Karp does the same job with hashing. When would you prefer it, and what is its worst case?
  • Find the longest prefix of the pattern that is also a suffix of it. Which single table entry is that?
  • The text arrives as a stream you cannot rewind and the pattern is fixed. Does anything need to change?

Related questions