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.
0/39 solved
Recognise it
The signal
Find a pattern in text, longest prefix that is also a suffix (border), periodicity / repeated pattern, shortest palindrome by prepending.
1Brute force
Compare at every shift: O(nm).
2The observation
Re-matching characters after a mismatch: the failure function reuses the matched border.
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
- 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 + '#' + tmust 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
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