String Matching

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.

Race four matchers

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

Every Place the Pattern Fits

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.

Slide the pattern one place at a time

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.

Say it aloud

C equals n minus m plus one, times m.

C
C the comparisons the naive matcher makes in the worst case.
n
n the length of the text T.
n − m + 1
n minus m plus one the number of shifts, s = 0 to s = n − m.
×
times each shift pays the same worst-case price.
m
m the length of the pattern P: the most one shift can read.
In plain words

Count the shifts, n − m + 1. Charge each shift m comparisons. Multiply to get C.

With numbers

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).

The road

  1. Strings as numbers: turn a pattern into one number you can compare in one step.
  2. The rolling hash: Rabin-Karp updates the window's number in constant time. The hero's blue window.
  3. Spurious hits: when two strings share a number, and how the modulus q controls it.
  4. The matching automaton: a machine that reads each character once. The hero's purple state.
  5. The prefix function: the small table that tells you where to fall back.
  6. KMP: fall back in the pattern, never back up in the text.
  7. Why KMP is linear: at most 2n comparisons, proved with a counter.
  8. The race: all four matchers on your own text (the showcase).
  9. Beyond CLRS: Boyer-Moore skips, and matchers for many patterns.
  10. The field guide: terms, numbers, code and the credit.
The naive matcher searches for abc in ababcabc. How many character comparisons does it make in total?

Chapter 1

Strings as Numbers

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].

Say it aloud

h-i-plus-one equals d times h-i, plus P of i, all mod q.

hi+1
h-i-plus-one the hash of the first i + 1 characters.
d
d the base: the alphabet size, 10 for digits.
hi
h-i the hash so far; h0 = 0.
P[i]
P of i the value of the next character.
mod q
mod q keep the remainder after dividing by the prime q, a number from 0 to q − 1.
In plain words

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.

With numbers

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.

Build a hash one digit at a time

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.

With d = 10 and q = 13, two windows hash to 7. What do you know?

Chapter 2

Rabin-Karp: The Rolling Hash

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.

Say it aloud

t-s-plus-one equals d times, t-s minus T of s times h, plus T of s plus m, all mod q.

ts+1
t-s-plus-one the hash of the next window, T[s+1..s+m].
d
d the base; multiplying by d moves every digit one place left.
ts
t-s the hash of the window now, T[s..s+m−1].
T[s]
T of s the character that leaves on the left.
h
h d to the m minus one, mod q: what the leading digit is worth.
T[s+m]
T of s plus m the character that enters on the right.
mod q
mod q keep the remainder; add q first if the result is negative.
In plain words

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.

With numbers

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.

Roll the window along the text

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.

Why does Rabin-Karp still compare characters when ts equals p?

Chapter 3

Spurious Hits and the Choice of q

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.

Say it aloud

E is about n minus m plus one, divided by q.

E
E the average number of spurious hits over many texts.
n − m + 1
n minus m plus one the number of windows the matcher hashes.
/ q
divided by q each window lands on p with chance 1 in q.
In plain words

Count the windows. Give each a 1 in q chance of sharing the pattern's hash. The product is E.

With numbers

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.

Turn up the prime

The line is the formula. The dots are spurious hits counted on one fixed text of 1,000 random digits. Drag q.

13

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.

A text has 10,001 windows and q = 101. About how many spurious hits do you expect?

Chapter 4

A Machine That Remembers

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).

Say it aloud

delta of q and a equals sigma of P-q followed by a.

δ(q, a)
delta of q and a the next state after reading character a in state q.
σ
sigma the suffix function: the longest prefix of P that ends the string.
Pq
P-q the first q characters of P: what state q has matched.
a
a the text character just read.
In plain words

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.

With numbers

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.

Run the automaton over the text

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.

For P = aab, the machine is in state 2 (it has matched aa) and reads a. What is the next state?

Chapter 5

The Prefix Function

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.

Say it aloud

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.

pi[i]
pi of i the length of the longest border of P[0..i].
max
the largest of all lengths that pass the test.
k < i + 1
k below i plus one a length shorter than the prefix: proper.
P[0..k−1]
P from zero to k minus one the first k characters.
P[i−k+1..i]
P from i minus k plus one to i the k characters that end at i.
In plain words

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].

With numbers

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].

Match the pattern against itself

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].

What is the prefix function of abcabc?

Chapter 6

KMP: Fall Back, Never Back Up

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]:

  1. If they agree, add 1 to q and move to the next text character.
  2. If they differ and q > 0, set q to pi[q − 1]. Compare the same text character again.
  3. If they differ and q = 0, move to the next text character.
  4. If q reaches m, report the shift i − m + 1. Then set q to pi[m − 1] to look for overlaps.

Fall back in the pattern

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.

KMP has q = 4 for ababc and the text character fails against c. What does it do next?

Chapter 7

Why KMP Is Linear

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.

Say it aloud

C equals n plus F, which is at most two n.

C
C all character comparisons KMP makes on the text.
n
n one final comparison for each text character.
F
F the fall-backs: mismatches with q > 0, each lowering q.
≤
is at most because F cannot exceed the rises of q, and those are at most n.
2n
two n the bound, whatever the pattern.
In plain words

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.

With numbers

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.

Watch the balance rise and fall

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.

Why can the fall-backs never exceed n?

Chapter 8

The Race

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.

Race them on your text

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 / patternNaiveRabin-KarpAutomatonKMP
14 a's, b / aaab48161526
abcxabcxabcxabcyabcxabcy / abcxabcy48332426
the cat sat on that mat / that28262327

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.

On ordinary English text, why do all four matchers make about n steps?

Chapter 9

Beyond CLRS: Skipping Ahead

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.

Say it aloud

The shift equals the larger of one and j minus last of c.

shift
shift how far the pattern moves right.
max(1, …)
the larger of one and so the pattern never moves left.
j
j the pattern position where the right-to-left comparison failed.
last[c]
last of c the last position of the failing text character in P, or −1.
In plain words

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.

With numbers

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.

Jump past what cannot match

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:

ToolIdeaUse it when
Aho-Corasicka trie of all patterns plus pi-like failure linksmany patterns, one pass over the text
Suffix arrayall suffixes of the text, sorted; binary searchone fixed text, many different patterns
Z-algorithmZ[i] = longest match of the text at i with its startsame 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.

The comparison fails at j = 6 on a text character that occurs at position 1 of the pattern. How far does the bad-character rule shift?

Chapter 10

The Field Guide

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.

Which matcher

MatcherPreprocessingMatchingUse it for
NaivenoneO((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
AutomatonO(m|Σ|) with piΘ(n)small alphabets, one lookup per character
KMPΘ(m)Θ(n), at most 2n comparisonsguaranteed linear time, streams
Boyer-Moore (bad character)O(m + |Σ|)often sublinear, worst O(nm)long patterns, large alphabets

Terms and numbers

TermMeaningNumber on this page
Valid shifts with T[s..s+m−1] = Ps = 4 for ababc in ababababcab
Naive worst case(n − m + 1) × m comparisons68 for aaab in 19 a's and a b
Hash ppattern value mod q, by Horner's rule31415 mod 13 = 7
Rolling hashdrop T[s], add T[s+m]t0 = 8, t1 = 9
Spurious hitequal hash, different string67399 at shift 12; expect (n − m + 1)/q
δ(q, a)σ(Pqa)δ(4, a) = 3 for ababc
Prefix functionlongest proper border of P[0..i]ababaca: [0, 0, 1, 2, 3, 0, 1]
KMP boundC = n + F ≤ 2n36 ≤ 40; 13 for the running example
Periodm − pi[m − 1]abcabcab: 3
Bad-character shiftmax(1, j − last[c])7, then 2; 15 comparisons in all

Before you trust a string search

  1. Test the worst case: a run of one letter, and a pattern of that letter ending in another.
  2. In Rabin-Karp, check characters on every hash hit, and keep every hash non-negative.
  3. Use h = dm−1 mod q, not dm.
  4. Check your prefix function on ababaca against [0, 0, 1, 2, 3, 0, 1].
  5. After a KMP match, set q to pi[m − 1] so the matcher finds overlaps.
  6. On large alphabets, prefer KMP to a full automaton table.

The core code

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]

Where it sits

Keep going

The takeaway. A failed comparison still tells you what the text holds. Rabin-Karp keeps it as a number, the automaton as a state, and KMP as one table of borders, so the text pointer never goes back.
You must search a stream of network bytes for one fixed pattern, and you cannot keep old bytes. Which matcher fits?

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.

Source

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.

CLRS Chapter 32 · String Matching
Next: Computational Geometry · Back to Gleams