Pattern matching
Finding a pattern of length m in a text of length n naively costs O(n × m). KMP and the Z-function reuse what earlier comparisons already proved, so they never move backwards in the text and run in O(n + m). Rabin-Karp compares rolling hashes instead, and Boyer-Moore skips ahead using the last character that failed.
How to recognise it
- Find where (or whether) one string appears inside another, possibly many times.
- The question is about prefixes that are also suffixes (borders), or the longest palindromic prefix.
- n and m are both large, so O(n × m) is too slow.
The idea in one picture
Slide the pattern along the text like a ruler. The naive way, after a mismatch, slides the ruler one step and starts comparing from scratch. The smart ways remember what the last attempt proved, and jump the ruler as far as that proof allows.
Four methods
| Method | Key idea | Time | Problems here |
|---|---|---|---|
| KMP | lps: after a mismatch, keep the longest part that still matches | O(n + m) | First Occurrence, Shortest Palindrome, Happy Prefix |
| Z-function | z[i]: how far s[i..] matches the start of s | O(n + m) | Z function |
| Rabin-Karp | rolling hash of each window, check letters on a hash match | O(n + m) expected | Rabin Karp |
| Boyer-Moore (bad character) | compare from the right, shift past the bad character | often sublinear, O(n × m) worst | Boyer Moore |
Template: the KMP prefix function
lps = array of m zeros, len = 0, i = 1
while i < m:
if p[i] == p[len]: len = len + 1; lps[i] = len; i = i + 1
else if len > 0: len = lps[len - 1] # try the next shorter border
else: lps[i] = 0; i = i + 1
The same function solves border questions directly: lps[m - 1] is the longest prefix that is also a suffix. Running
it on s + "#" + reverse(s) gives the longest palindromic prefix of s.
Common mistakes
- Moving the text index backwards after a mismatch, which brings back the O(n × m) cost.
- Forgetting the separator in
pattern + "$" + text, so matches run across the join. - Trusting a hash match without comparing the letters.
- Off-by-one errors when turning a position in the joined string back into a text index.
Problems
- Find the Index of the First Occurrence in a Stringeasyguide ready
- Rabin Karp Algorithmhardguide ready
- Z functionhardguide ready
- Shortest Palindromehardguide ready
- Longest Happy Prefixhardguide ready
- Boyer Moore Algorithm for Pattern Searchinghardguide ready