String matching asks where a pattern P of length m occurs inside a text T of length n. The naive approach can take O(n·m) time because it forgets everything it learned after each mismatch. KMP remembers it with a failure function, Rabin-Karp compares fingerprints with a rolling hash, and the Z-algorithm measures prefix matches everywhere at once. All three run in linear time (Rabin-Karp in expectation), and they underpin search tools, plagiarism checkers and DNA analysis.
Think of it like
Rereading a sentence you already know
Suppose you are scanning a page for the phrase "abracadabra" and you have matched "abracad" when the next letter is wrong. A careless reader shifts by one letter and starts over. A smart reader notices that the "a" at the end of what they just read is also how the phrase begins, so they keep that "a" and continue from there, without ever rereading the page. KMP precomputes exactly how much of the phrase can be kept after each possible mismatch.
The problem
Given text T (length n) and pattern P (length m), report every index i with T[i .. i+m-1] == P. Typical sizes make the difference between O(n·m) and O(n + m) matter: searching a 10 MB log for a 1 KB pattern is 10¹⁰ character comparisons in the worst naive case versus about 10⁷ for a linear algorithm.
Naive matching
def naive_search(t: str, p: str) -> list[int]:
n, m = len(t), len(p)
hits = []
for i in range(n - m + 1): # every possible alignment
j = 0
while j < m and t[i + j] == p[j]:
j += 1
if j == m:
hits.append(i)
return hitsOn ordinary text, mismatches happen quickly and the naive search is fast. The worst case is repetitive input: T = "aaaa…a" and P = "aaa…ab" match m - 1 characters at every alignment before failing, giving Θ(n·m) comparisons.
Knuth-Morris-Pratt (KMP)
KMP never moves backward in the text. When a mismatch happens after matching j characters, it slides the pattern so that the longest prefix of P that is also a suffix of the matched part stays aligned, then keeps comparing from there. That shift amount depends only on the pattern, so it is precomputed in an array called the LPS (longest proper prefix which is also a suffix) or failure function.
- Proper prefix
- A prefix that is not the whole string. The proper prefixes of
"abab"are"","a","ab","aba". - lps[i]
- Length of the longest proper prefix of
P[0..i]that is also a suffix ofP[0..i]. - Fallback
- On a mismatch after matching j characters, continue with
j = lps[j - 1]instead of restarting from 0.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| P[i] | A | B | A | B | C | A | B | A | B |
| lps[i] | 0 | 0 | 1 | 2 | 0 | 1 | 2 | 3 | 4 |
ABABCABAB. At i = 8, the prefix ABAB equals the suffix ABAB of ABABCABAB, so lps[8] = 4.Building the LPS array is itself KMP: the pattern is matched against itself. Keep len, the length of the current matching prefix. If P[i] == P[len], extend it. Otherwise fall back with len = lps[len - 1] and try again, and only when len reaches 0 record lps[i] = 0.
- 1
Compare
Compare
T[i]withP[j], wherejis the number of pattern characters currently matched. - 2
Match
If equal, advance both
iandj. Ifj == m, report a match ati - mand setj = lps[m - 1]to look for overlapping matches. - 3
Mismatch with j > 0
Set
j = lps[j - 1]and compareT[i]again. The text pointer does not move. - 4
Mismatch with j == 0
No prefix can be kept. Advance
i.
The visualization above plays this loop: the text pointer only ever moves right, while the pattern jumps forward by the amount the LPS table allows on each mismatch.
Rabin-Karp: rolling hashes
Rabin-Karp compares numbers instead of strings. It hashes the pattern once, then hashes each length-m window of the text. When the hashes differ, the window certainly does not match. When they agree, it verifies character by character, because different strings can share a hash. The trick is computing each window's hash from the previous one in O(1).
yellow vs ifbank collides even with this large prime, and the M = 101 preset collides constantly: in both, only verification stops a false match.Expected case: O(n + m)
- With a random base and a large prime, a false match (collision) has probability about 1/M per window
- Verification runs only on real matches plus rare collisions
- Easy to extend to many patterns of the same length via a hash set
Worst case: O(n·m)
- Many spurious hits (a weak hash, a tiny modulus, or adversarial input)
- Or a pattern that genuinely occurs at almost every position, such as
aaainaaaa… - Every hit costs O(m) to verify
Rolling hashes shine beyond single-pattern search: finding repeated substrings of length k (Repeated DNA Sequences), comparing any two substrings in O(1) after O(n) preprocessing of prefix hashes, Longest Duplicate Substring (binary search on the length plus hashing), and 2D pattern matching. See Hash Tables for hashing fundamentals.
The Z-algorithm
For a string S, Z[i] is the length of the longest substring starting at i that matches a prefix of S. The algorithm maintains the rightmost Z-box [l, r): a segment known to equal a prefix. For a position inside the box, the answer is at least min(r - i, Z[i - l]) for free; only characters beyond r need fresh comparisons, so the whole array is computed in O(n).
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| S[i] | a | a | b | x | a | a | b |
| Z[i] | 7 | 1 | 0 | 0 | 3 | 1 | 0 |
aabxaab. Z[4] = 3 because aab starting at index 4 matches the prefix aab. Z[0] is conventionally n (or left undefined).To search, compute Z on P + T (often written P + "$" + T with a separator that occurs in neither string). Every position i ≥ m with Z[i] ≥ m marks an occurrence of P starting at i - m in T. Even without a separator this works, as long as you only consider positions inside T and test Z[i] ≥ m.
S = P + T without a separator. The first preset rebuilds the table above (aab + xaab). Watch positions inside the Z-box copy their value from the mirror i − l for free, while only characters past r are compared.Beyond a single pattern
Boyer-Moore
Boyer-Moore compares the pattern right to left. On a mismatch, the bad-character rule shifts the pattern so the mismatched text character lines up with its last occurrence in the pattern (or past it entirely), and the good-suffix rule reuses the suffix that did match. With a large alphabet, most shifts skip nearly m characters, so the best case reads only about n/m characters: sublinear. Variants such as Boyer-Moore-Horspool are the workhorses behind fast grep-style tools.
Aho-Corasick
To search for many patterns at once (a dictionary of banned words, virus signatures), build a Tries (Prefix Trees) of all patterns and add KMP-style failure links between trie nodes. Scanning the text once then reports every occurrence of every pattern in O(n + total pattern length + number of matches).
Suffix arrays
A suffix array lists the starting positions of all suffixes of T in sorted order. Build it in O(n log n) with prefix doubling (O(n log² n) with a simple comparison sort, O(n) with SA-IS). Once built, any pattern is found by binary search in O(m log n), and the companion LCP array (Kasai's algorithm, O(n)) answers questions such as the longest repeated substring or the number of distinct substrings. Suffix arrays are the space-efficient cousin of suffix trees.
Choosing an algorithm
| Algorithm | Preprocessing | Search | Extra space | Best for |
|---|---|---|---|---|
| Naive | None | O(n·m) worst | O(1) | Short patterns, non-repetitive text |
| KMP | O(m) | O(n) | O(m) | Guaranteed linear time, streaming text |
| Rabin-Karp | O(m) | O(n) expected | O(1) | Many same-length patterns, substring hashing |
| Z-algorithm | None | O(n + m) | O(n + m) | Prefix-overlap questions, quick to code |
| Boyer-Moore | O(m + σ) | O(n/m) best, O(n + m) worst with Galil's rule | O(m + σ) | Long patterns, large alphabets |
| Aho-Corasick | O(Σ|Pᵢ|) | O(n + matches) | O(Σ|Pᵢ| · σ) | Many patterns at once |
| Suffix array | O(n log n) | O(m log n) per query | O(n) | Many queries on one fixed text |
Applications
- Text editors and command-line search (
grep, find-in-page). - Intrusion detection and antivirus scanning with thousands of signatures (Aho-Corasick).
- Bioinformatics: locating DNA motifs and aligning reads against a reference genome (suffix arrays and FM-indexes).
- Plagiarism and near-duplicate detection with rolling-hash fingerprints (winnowing, as in MOSS).
- Data deduplication and rsync's rolling checksum for finding unchanged blocks.
- Full-text search engines, see Search Systems.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Naive | O(n·m) | O(1) | Fast on typical text |
| KMP | O(n + m) | O(m) | Worst-case linear |
| Rabin-Karp | O(n + m) | O(1) | Expected; worst case O(n·m) |
| Z-algorithm | O(n + m) | O(n + m) | Z-array of P + T |
| Boyer-Moore | O(n/m) | O(m + σ) | Best case; sublinear |
| Aho-Corasick | O(n + Σ|Pᵢ| + z) | O(Σ|Pᵢ|) | z = number of matches |
| Suffix array build | O(n log n) | O(n) | Then O(m log n) per query |
Implementation
Build the LPS array, then scan the text once without ever moving backward.
def build_lps(p: str) -> list[int]:
lps = [0] * len(p)
length = 0 # length of the current matching prefix
for i in range(1, len(p)):
while length > 0 and p[i] != p[length]:
length = lps[length - 1] # fall back to a shorter border
if p[i] == p[length]:
length += 1
lps[i] = length
return lps
def kmp_search(t: str, p: str) -> list[int]:
if not p:
return []
lps = build_lps(p)
hits: list[int] = []
j = 0 # pattern characters matched so far
for i, c in enumerate(t):
while j > 0 and c != p[j]:
j = lps[j - 1] # keep the longest border; i does not move back
if c == p[j]:
j += 1
if j == len(p):
hits.append(i - len(p) + 1)
j = lps[j - 1] # allow overlapping matches
return hitsKey takeaways
- Naive matching is O(n·m) in the worst case because it forgets what it learned after each mismatch.
- KMP precomputes the LPS (failure) array so the text pointer never moves backward: O(n + m) guaranteed.
- Rabin-Karp compares rolling hashes in O(1) per window: expected O(n + m), but always verify to handle collisions.
- The Z-algorithm computes prefix-match lengths everywhere in O(n); search by computing Z on
P + T. - For many patterns use Aho-Corasick; for many queries on one text use a suffix array; for long patterns on large alphabets, Boyer-Moore.
Common pitfalls
- Resetting
jto 0 on a mismatch in KMP instead of falling back withlps[j - 1], which misses matches. - Moving the text pointer backward, which destroys the linear-time guarantee.
- Reporting a Rabin-Karp match without verifying, or using a tiny or fixed modulus that adversarial input can collide.
- Getting a negative hash after subtracting the outgoing character; add the modulus before taking the remainder.
- Forgetting overlapping matches (after a full match, continue from
lps[m - 1], not 0).
Interview tips
- Be able to compute an LPS array by hand for a short pattern such as
AABAAB; interviewers often ask. - Explain KMP's amortized argument: j increases at most n times and every fallback decreases it.
- Reach for a rolling hash when the problem involves comparing many substrings of the same length.
Real-world applications
- Search features in editors, browsers and command-line tools.
- Network intrusion detection and antivirus engines (multi-pattern matching).
- Genome analysis with suffix arrays and FM-indexes.
- Plagiarism detection and deduplication with rolling-hash fingerprints.
Practice problems
Test yourself
What is the LPS (failure function) array of the pattern AAAA?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.