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)

O(n + m)

Precompute a prefix-function (KMP) so a mismatch skips ahead without rescanning, or use a rolling hash.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksManacher's AlgorithmAho-Corasick Automaton
0%
mastery
0/39 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Find a pattern in text, longest prefix that is also a suffix (border), periodicity / repeated pattern, shortest palindrome by prepending.

  1. 1Brute force

    Compare at every shift: O(nm).

  2. 2The observation

    Re-matching characters after a mismatch: the failure function reuses the matched border.

  3. 3Why it works

    pi[i] is the length of the longest proper border of s[:i+1].

Reach for it when

  • +longest prefix that is also a suffix (border)
  • +periodicity / repeated pattern
  • +shortest palindrome by adding a prefix

Not when

  • ×Many patterns at onceuse Aho-Corasick
  • ×Substring order or LCP queriesuse Suffix array
  • ×Palindromic substringsuse Manacher

Practice

Next · Foundation

Find the Index of the First Occurrence in a String

Implement prefix function / KMP rather than brute force.

0/39 solved
  • Find the Index of the First Occurrence in a StringFoundationFoundationMeta, AmazonEasy
  • String MatchingApply it · Count occurrences at 1e6.Apply itCSESMedium
  • Longest Happy PrefixOne change · Longest border.One changeHard
  • Finding BordersOne change · All borders.One changeCSESMedium
  • Repeated Substring PatternTwists · Periodicity, not matching.TwistsEasy
  • Finding PeriodsBranches · All periods.BranchesCSESMedium
  • Repeated DNA SequencesBranches · Fixed-length repeated substrings.BranchesMedium
  • Shortest PalindromeCombine · Palindrome via matching.CombineHard
  • Longest Duplicate SubstringMastery checkMastery checkHard
  • Longest Common PrefixAdobe, AmazonEasy
  • Reverse StringApple, AdobeEasy
  • Roman to IntegerAmazon, AdobeEasy

Pitfalls

Classic bugs

  • !Hashing variant: a single small modulus collides; use a large or double modulus.
  • !The separator in s + '#' + t must not appear in either string.
Go deepervariants and techniques · 2 combinations · resources

Variants and techniques

  • Rolling / Polynomial String HashingHash every substring in O(1) after O(n) prefix-hash precomputation, enabling substring equality checks, often combined with binary search on length.
  • Suffix Array + LCPSort all suffixes (O(n log n)) and compute LCP of neighbours to answer distinct-substring, repeated-substring, and pattern-count questions.

Combinations

  • Bitmask DP+String Matching (KMP / Z / Rabin-Karp)

    shortest superstring containing all words (n <= 12)

    Bitmask DP:
    TSP over strings
    String Matching (KMP / Z / Rabin-Karp):
    pairwise overlaps; with at most 12 short words brute force is enough, borders (KMP) only matter at larger sizes

    Find the Shortest Superstring

  • FFT / NTT Convolution (and Walsh-Hadamard)+String Matching (KMP / Z / Rabin-Karp)

    pattern matching with wildcards, or counting mismatches/near-matches for every alignment

    FFT / NTT Convolution (and Walsh-Hadamard):
    for each alphabet letter, convolve the indicator arrays to count matches at every shift
    String Matching (KMP / Z / Rabin-Karp):
    the matching-per-shift question

    Fuzzy SearchSubstring Search

Resources

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

Template · clean C++, Java and Python to revise from

Start the free 7-day trial