Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Strings & Tries/String Matching (KMP / Z / Rabin-Karp)

Technique

Rolling / Polynomial String Hashing

Hash every substring in O(1) after O(n) prefix-hash precomputation, enabling substring equality checks, often combined with binary search on length.

Learn firstString Matching (KMP / Z / Rabin-Karp)Prefix SumUnlocksSuffix Array + LCP
0%
mastery
0/7 solved
Practise nextRepeated DNA Sequences
IdeaPracticePitfalls

Recognise it

The signal

compare many substrings

  1. 1Brute force

    Compare substrings character by character.

  2. 2The observation

    O(length) comparisons: equal hashes mean equal strings with high probability.

  3. 3Why it works

    H[i] = sum s[j] * p^(i-1-j) mod M, so hash(l, r) = H[r] - H[l] * p^(r-l).

Reach for it when

  • +longest repeated / common substring with binary search on length
  • +count distinct substrings of a fixed length

Not when

  • ×anti-hash tests on CF with fixed base/mod
  • ×exactness required (use suffix-array / KMP)

Practice

Next

Repeated DNA Sequences

0/7 solved
  • Repeated DNA SequencesMedium
  • Palindrome QueriesCSESMedium
  • Prefix-Suffix Palindrome (Hard version)Codeforces1800
  • Longest Duplicate SubstringHard
  • Repeating SubstringCSESHard
  • Compress WordsCodeforces2000
  • Longest Happy PrefixHard

Pitfalls

Misconceptions

  • !one 32-bit modulus with many comparisons collides (birthday bound)
Go deeperresources

Resources

  • Prefix function (KMP)cp-algorithms · article
  • Z-functioncp-algorithms · article
  • String hashingcp-algorithms · article
  • Trie explore cardLeetCode · course
  • String cheatsheetTech Interview Handbook · article
TodayReviewPatternsProblems