Find aaab in nineteen a's and a b. The naive matcher makes 68 character comparisons. KMP makes 36. The automaton reads each of the 20 characters once.
Pick a matcher and press Play. Then switch the text. Then we build, piece by piece, the naive matcher, the rolling hash of Rabin-Karp, the matching automaton and the prefix function behind Knuth-Morris-Pratt.
You need a little Python and the remainder of a division (17 mod 5 is 2). We build the rest from zero.
Based on Chapter 32, String Matching, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Number-Theoretic Algorithms. Next: Computational Geometry.
One step is one character comparison (naive, KMP), one table lookup (automaton), or one hash check plus each character checked after the hashes agree (Rabin-Karp, q = 13). The texts are toy examples; the digit text is the Rabin-Karp example in CLRS.
Chapter 0
Slide the pattern one place at a time, and count how often you read the same character
You press Ctrl+F and type ababc. The editor must find every place where those five letters appear. The document is the text T, with n characters. The search string is the pattern P, with m characters.
Put the pattern under the text, starting at position s. That offset is a shift. A shift is valid if all m characters agree. The task is to report every valid shift, from s = 0 to s = n − m.
The naive matcher tries every shift. It compares left to right and stops at the first mismatch. Step it below and watch the heat row: it counts how many times each text character is read.
Teal means the characters agree, red means they differ. The yellow bars under the text count reads. Press Step or Play.
Text ababababcab, pattern ababc: the running example of this page. The naive matcher makes 21 comparisons and finds one valid shift, s = 4.
The waste is plain. At shift 0 the matcher learns that T[0..3] is abab. At shift 1 it forgets that and reads T[1] again. Every method in this chapter keeps that knowledge in some form.
How bad can it get? Take the length of the text n and the length of the pattern m. The matcher tries n − m + 1 shifts. In the worst case each shift reads all m characters. Call the total number of comparisons C.
C equals n minus m plus one, times m.
Count the shifts, n − m + 1. Charge each shift m comparisons. Multiply to get C.
The hero text has nineteen a's and a b, so n = 20. The pattern aaab has m = 4. C = (20 − 4 + 1) × 4 = 17 × 4 = 68. Every shift reads three a's and then decides on the fourth character.
For n = 1,000,000 and m = 1,000, C is 999,001 × 1,000, about 109 comparisons. A method that reads each character a fixed number of times needs about 106.
The failure. Symptom: a search is fast on prose and hangs on a log with long runs of one byte, or on DNA. Measure: count comparisons and divide by n; a ratio near m means the worst case. Fix: a matcher that never reads a text character twice, such as KMP (Chapter 6).
abc in ababcabc. How many character comparisons does it make in total?Chapter 1
Read a pattern as one number, and keep that number small with a remainder
Comparing two strings of length m costs up to m steps. Comparing two numbers costs one. So read the string as a number. The digit string 31415 is the number 31,415.
A string over an alphabet of d letters is a number in base d. For digits, d = 10. For bytes, d = 256 and each character's code is its digit. Horner's rule builds the number one character at a time: multiply what you have by d, then add the next digit.
The numbers grow fast. Five bytes already need 40 bits. So keep only the remainder after division by a fixed prime q. That remainder is the hash of the string. Call the hash after the first i characters hi, and the next character P[i].
h-i-plus-one equals d times h-i, plus P of i, all mod q.
Start with h = 0. For each character, multiply h by d, add the character P[i], and keep the remainder mod q. After m characters, h is the hash p of the pattern.
P = 31415, d = 10, q = 13. The hash goes 3, then (30 + 1) mod 13 = 5, then (50 + 4) mod 13 = 2. Next (20 + 1) mod 13 = 8, and (80 + 5) mod 13 = 7. So p = 7, the same as 31,415 mod 13.
Pick a pattern and a prime q. Press Step to fold in one more digit. The blue number never grows past q − 1.
Digits use their value and d = 10. Try 67399 with q = 13: it also hashes to 7.
The remainder makes the hash cheap. It also throws information away. With q = 13 there are only 13 possible hashes, so 31415 and 67399 share one. Equal hashes say "maybe equal". Different hashes say "certainly different".
The failure. Symptom: hashes differ between two runs of the same code in C or Java. Measure: print the hash before the mod at each step; it overflows a 64-bit integer. Fix: take the mod after every step, and pick q so that d × q fits in a machine word.
Chapter 2
Drop one digit, add one digit, and get the next window's hash in constant time
Rabin-Karp hashes the pattern once. Then it slides a window of m characters along the text and compares the window's hash with the pattern's hash. Hashing each window from scratch would cost m steps per window, no better than naive.
The trick: the next window shares m − 1 characters with this one. In decimal, 23590 becomes 35902. Remove the leading 2 (worth 2 × 104), multiply by 10, add the new digit 2. Call the hash of the window at shift s ts, and the place value of the leading digit h = dm−1 mod q.
t-s-plus-one equals d times, t-s minus T of s times h, plus T of s plus m, all mod q.
Take the old hash t-s. Subtract the leaving character T[s] times h. Multiply by d. Add the entering character T[s+m]. Keep the remainder mod q.
T = 2359023141526739921, m = 5, q = 13, so h = 104 mod 13 = 3. The first window 23590 has t0 = 8. Then t1 = (10 × (8 − 2 × 3) + 2) mod 13 = 22 mod 13 = 9, and 35902 mod 13 is 9 too.
The pattern 31415 hashes to p = 7. Each step rolls the window one place. A green window is a match; a red one is a spurious hit.
The text, pattern and q = 13 are the Rabin-Karp example in CLRS. We checked every window hash in Python.
Of 15 windows, two hash to 7. The window at shift 6 is 31415, a valid shift. The window at shift 12 is 67399, a spurious hit: the hashes agree but the strings do not. Rabin-Karp checks the characters of every hash hit, so it never reports a spurious hit as a match.
The failure. Symptom: the C version misses matches that the Python version finds. Measure: print ts; some values are negative. In C, −5 % 13 is −5, not 8. Fix: add q before the final mod.
Chapter 3
Turn q up and watch the false alarms disappear
Each spurious hit costs up to m character checks. How many should you expect? Picture the window hashes as numbers spread evenly from 0 to q − 1. Then a window that does not match still lands on p one time in q. CLRS makes this same assumption.
Call the number of windows n − m + 1, and the expected number of spurious hits E.
E is about n minus m plus one, divided by q.
Count the windows. Give each a 1 in q chance of sharing the pattern's hash. The product is E.
A text of 1,000 random digits and a pattern of 5 give 996 windows. With q = 13, E ≈ 996 / 13 = 76.6. With q = 1,000,000,007, E ≈ 0.000001: almost never.
The line is the formula. The dots are spurious hits counted on one fixed text of 1,000 random digits. Drag q.
A fixed pseudo-random rule in the page makes the text; the pattern is 31415. Counts on one text scatter around the formula.
CLRS writes the expected matching time as O(n) + O(m(v + n/q)), where v is the number of valid shifts. If v is small and q is larger than m, the total is O(n + m). The guarantee is only on average. With q = 1, every window is a hit, and Rabin-Karp falls back to the naive cost (n − m + 1) × m.
The failure. Symptom: a hash search slows down on text an attacker can choose. Measure: count spurious hits; far more than n/q means the text targets your q. Fix: pick q at random from many large primes when the program starts.
Rabin-Karp shines with many patterns of one length. Put all their hashes in a set. Each window costs one lookup, for ten patterns or ten thousand.
Chapter 4
Precompute where to go after every character, then read the text once
The naive matcher forgets what it read. A finite automaton keeps it in one number, the state q. The state is the length of the longest prefix of P that ends at the current text position. State 0 means nothing matches. State m means the whole pattern just ended here.
When the next character a arrives, the new state is fixed by the old state and a. Write Pq for the first q characters of P. Call the length of the longest prefix of P that is also a suffix of a string x the suffix function σ(x). The table entry for state q and character a is δ(q, a).
delta of q and a equals sigma of P-q followed by a.
Write down what state q has matched, P-q. Append the new character a. Find the longest prefix of P that ends that string. Its length is the next state.
P = ababc. In state 4 you have matched abab. Read a: the string is ababa. The prefixes ababc and abab do not end it; aba does. So δ(4, a) = 3.
The purple ring is the state. The table row is that state; the lit cell is the lookup for the next character. Press Step or Play.
Pattern ababc over the alphabet {a, b, c}, text ababababcab. We computed the table from σ in Python.
The run takes 11 lookups for 11 characters and reaches state 5 at position 8, so the valid shift is 8 − 5 + 1 = 4. After a match it keeps going: δ(5, a) = 1, so the machine also finds overlapping matches.
The cost moves into the table: (m + 1) rows times |Σ| columns, where |Σ| is the alphabet size. Filling it straight from σ costs O(m3|Σ|). With the prefix function of the next chapter it costs O(m|Σ|).
The failure. Symptom: the matcher runs out of memory on Unicode text. Measure: rows times columns; m = 20 over 256 byte values is 5,376 entries, and over every Unicode code point it is millions. Fix: keep only the fall-back links, which is KMP.
Chapter 5
Find, for each prefix of the pattern, the longest part that both starts and ends it
Look at abab. Its first two letters, ab, are also its last two. A string that is both a proper prefix (shorter than the whole) and a suffix is a border. If you have matched abab and the next character fails, the border ab is still matched. You can continue from there.
The prefix function stores the longest border of each prefix. This page counts from 0, so pi[i] belongs to P[0..i]. CLRS counts from 1 and writes π[q] for the first q characters; it is the same table.
pi of i equals the largest k below i plus one, such that P zero to k minus one equals P i minus k plus one to i.
Take the prefix that ends at i. Try lengths k from long to short. The first k whose first k characters equal its last k characters is pi[i].
P = ababaca. P[0..4] = ababa: k = 3 works, since aba starts and ends it, so pi[4] = 3. P[0..5] = ababac ends in c and no border ends in c, so pi[5] = 0. In full, pi = [0, 0, 1, 2, 3, 0, 1].
The lower row is the pattern slid under itself by the current border length k. A red cell makes k fall back along the purple chain. Pick a pattern and step.
Each step is one character comparison of the loop in the code below.
The fast rule: pi[i] is at most pi[i − 1] + 1. So try to extend the last border by one character. If P[k] differs from P[i], the next border to try is pi[k − 1], the longest border of the border. Take aabaaab at i = 5. The test at k = 2 fails (b against a), so k falls to pi[1] = 1. Then P[1] = a matches, so pi[5] = 2.
The table also gives the period, the shortest shift that maps the string onto itself: m − pi[m − 1]. For abcabcab, 8 − 5 = 3.
The failure. Symptom: a ported KMP misses matches or reads past the end. Measure: compute pi for ababaca and compare with [0, 0, 1, 2, 3, 0, 1]. Fix: pick one indexing; with 0-based arrays, fall back with pi[k − 1], not pi[k].
Chapter 6
Use the prefix function to keep the text pointer moving forward
The Knuth-Morris-Pratt matcher (KMP) keeps two numbers. The text position i only goes forward. The matched length q says how many pattern characters end at i. Each step compares P[q] with T[i]:
The text pointer is the warm caret. Teal cells are the q characters known to match. On a red cell the pattern jumps right, and the purple arc shows the fall-back. Compare the count with naive's 21.
Text ababababcab, pattern ababc, pi = [0, 0, 1, 2, 0]. One step is one character comparison.
Trace the first mismatch. At i = 4 the matcher has q = 4 (abab) and compares P[4] = c with T[4] = a. They differ. The border of abab is ab, so q becomes pi[3] = 2, and the pattern now sits at shift 2. P[2] = a agrees with T[4] = a, so q becomes 3. Nobody re-read T[2] or T[3].
The whole run takes 13 comparisons against naive's 21. KMP is the automaton with the table squeezed into pi: m numbers instead of (m + 1) × |Σ|. The price is that one text character can cost several fall-backs. The next chapter shows this evens out.
The failure. Symptom: searching aa in aaaa returns 2 matches, not 3. Measure: look at what q becomes after a match. Fix: set q to pi[m − 1], not 0. Resetting to 0 skips the overlapping match at shift 1.
Chapter 7
Count the rises and falls of q, and the loop inside the loop costs at most 2n
KMP has a loop inside a loop. The inner loop can fall back many times for one character. So is it O(nm)? No. Watch the matched length q as a bank balance.
So split the comparisons into two kinds. Call the number of text characters n, the number of fall-backs F, and the total comparisons C.
C equals n plus F, which is at most two n.
Give every text character one final comparison: that is n. Add one comparison per fall-back: that is F. F is at most n, so C is at most 2n.
Hero text, nineteen a's and a b, pattern aaab: n = 20 and F = 16, so C = 36, under 2n = 40. The running example: n = 11 and F = 2, so C = 13.
Teal steps are agreements (q rises by 1). Purple drops are fall-backs. The yellow ruler is the total against its limit 2n. Pick a text.
Counts from the KMP code of this page. The third text is abcxabcxabcxabcyabcxabcy.
The same argument bounds the prefix function: at most 2m comparisons, about 2 × 7 = 14 for ababaca, which in fact takes 8. So KMP runs in O(n + m) time and needs only the m entries of pi.
The failure. Symptom: a code review flags the inner while loop as quadratic. Measure: count total comparisons on a run of a's; it stays under 2n. Fix: none needed; cite the balance argument.
Chapter 8
Run all four matchers on your own text and see where each one reads
Now put them side by side. Type a text and a pattern, or pick a preset. Each strip is the text, and the height of each bar is how many steps that matcher spent on that character.
Type, or tap a preset. Tall bars mean the matcher read that character many times. Green ticks mark valid shifts.
Rabin-Karp uses q = 13 (digits with d = 10, other text with d = 256), so spurious hits are visible. The page charges its hash check to the character that enters the window.
What the presets show, with counts from the code:
| Text / pattern | Naive | Rabin-Karp | Automaton | KMP |
|---|---|---|---|---|
| 14 a's, b / aaab | 48 | 16 | 15 | 26 |
| abcxabcxabcxabcyabcxabcy / abcxabcy | 48 | 33 | 24 | 26 |
| the cat sat on that mat / that | 28 | 26 | 23 | 27 |
On repetitive input, naive reads each character up to m times, and its strip turns into a tall wall. KMP never spends more than 2n in total. The automaton is flat: one lookup per character, paid for by its table. Rabin-Karp is flat too, until a hash hit forces a character check.
On prose all four land near n, because the first character usually fails. The differences are about guarantees, not typical speed. Choose KMP or the automaton when the input can be hostile or repetitive. Choose Rabin-Karp for many patterns of one length.
The failure. Symptom: a benchmark on English says naive is as fast as KMP, so the team ships naive. Measure: rerun on a run of a's with a pattern of a's ending in b. Fix: test the worst case, not the typical one.
Chapter 9
Compare from the right end, and jump past characters the pattern does not contain
Every matcher so far reads every text character. Boyer-Moore does not. It compares the window from right to left. On a mismatch it looks at the text character c that failed. It moves the pattern so that the last c in P lines up with it. If P has no c, the pattern jumps past it.
Call the pattern position of the mismatch j. Call the last position of c in P last[c], with last[c] = −1 if c is not in P.
The shift equals the larger of one and j minus last of c.
Find where the failing character c last occurs in the pattern. Move the pattern so that it sits under c. If that would move it left, move one place.
P = example (m = 7). The first window of "here is a simple example" is "here is". P[6] = e fails against s, so j = 6. The letter s is not in P, so last[s] = −1 and the shift is 6 − (−1) = 7.
Each step is one alignment. Comparisons run right to left. The red cell is the bad character; the arrow is the shift. Press Step.
Bad-character rule only, without the good-suffix rule. Counts checked in Python: 5 alignments, 15 comparisons; naive needs 27.
Five alignments find example at shift 17 with 15 comparisons. Long patterns over large alphabets jump far, so Boyer-Moore often reads only a fraction of the text. Its worst case with this rule alone is still (n − m + 1) × m.
Three more tools, for other shapes of the problem:
| Tool | Idea | Use it when |
|---|---|---|
| Aho-Corasick | a trie of all patterns plus pi-like failure links | many patterns, one pass over the text |
| Suffix array | all suffixes of the text, sorted; binary search | one fixed text, many different patterns |
| Z-algorithm | Z[i] = longest match of the text at i with its start | same job as pi, extending forward; Z for aabxaab is [7, 1, 0, 0, 3, 1, 0] |
The failure. Symptom: Boyer-Moore is slow on DNA. Measure: average shift; with 4 letters, every letter is in P and shifts stay short. Fix: on small alphabets use KMP or the automaton.
Chapter 10
Keep the matchers, the numbers, the checks and the core code on one page
Naive is fine on prose and quadratic on repetitive text. Rabin-Karp compares numbers and checks characters on a hash hit. The automaton reads each character once from a big table. KMP keeps the same guarantee with m numbers.
| Matcher | Preprocessing | Matching | Use it for |
|---|---|---|---|
| Naive | none | O((n − m + 1)m) | short or non-repetitive text |
| Rabin-Karp | Θ(m) | expected O(n + m), worst O((n − m + 1)m) | many patterns of one length |
| Automaton | O(m|Σ|) with pi | Θ(n) | small alphabets, one lookup per character |
| KMP | Θ(m) | Θ(n), at most 2n comparisons | guaranteed linear time, streams |
| Boyer-Moore (bad character) | O(m + |Σ|) | often sublinear, worst O(nm) | long patterns, large alphabets |
| Term | Meaning | Number on this page |
|---|---|---|
| Valid shift | s with T[s..s+m−1] = P | s = 4 for ababc in ababababcab |
| Naive worst case | (n − m + 1) × m comparisons | 68 for aaab in 19 a's and a b |
| Hash p | pattern value mod q, by Horner's rule | 31415 mod 13 = 7 |
| Rolling hash | drop T[s], add T[s+m] | t0 = 8, t1 = 9 |
| Spurious hit | equal hash, different string | 67399 at shift 12; expect (n − m + 1)/q |
| δ(q, a) | σ(Pqa) | δ(4, a) = 3 for ababc |
| Prefix function | longest proper border of P[0..i] | ababaca: [0, 0, 1, 2, 3, 0, 1] |
| KMP bound | C = n + F ≤ 2n | 36 ≤ 40; 13 for the running example |
| Period | m − pi[m − 1] | abcabcab: 3 |
| Bad-character shift | max(1, j − last[c]) | 7, then 2; 15 comparisons in all |
pythondef prefix_function(P): """pi[i] = length of the longest proper prefix of P[0..i] that is also its suffix.""" pi, k = [0] * len(P), 0 for i in range(1, len(P)): while k > 0 and P[k] != P[i]: k = pi[k - 1] # the border of the border if P[k] == P[i]: k += 1 pi[i] = k return pi def kmp(T, P): pi, q, hits = prefix_function(P), 0, [] for i, ch in enumerate(T): while q > 0 and P[q] != ch: q = pi[q - 1] # fall back; i stays put if P[q] == ch: q += 1 if q == len(P): hits.append(i - len(P) + 1) q = pi[q - 1] # keep overlaps return hits def rabin_karp(T, P, d=256, q=1_000_000_007): n, m = len(T), len(P) if m > n: return [] h = pow(d, m - 1, q) # what the leading character is worth p = t = 0 for i in range(m): # Horner's rule p = (d * p + ord(P[i])) % q t = (d * t + ord(T[i])) % q hits = [] for s in range(n - m + 1): if p == t and T[s:s + m] == P: # check: the hit may be spurious hits.append(s) if s < n - m: # roll: drop T[s], add T[s+m] t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q return hits print(prefix_function("ababaca")) # [0, 0, 1, 2, 3, 0, 1] print(kmp("ababababcab", "ababc")) # [4] print(kmp("aaaa", "aa")) # [0, 1, 2] print(rabin_karp("2359023141526739921", "31415")) # [6]
Now press Present or Teach. Explain from memory why naive is quadratic on runs of a's and how the rolling hash drops and adds a digit. Then say what a spurious hit is, and why KMP makes at most 2n comparisons. Then go back to the hero, pick the first text, and say why the automaton's bar is the shortest.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 32, String Matching. The naive matcher, Rabin-Karp, the string-matching automaton, the prefix function and KMP follow the book. This page counts from 0 where the book counts from 1. Boyer-Moore, Aho-Corasick, suffix arrays and the Z-algorithm go beyond the chapter. The Boyer-Moore sentence is a common teaching example. Other examples, devices and counts are our own.