String Matching: Rabin–Karp, KMP & the Z-Function
Finding a pattern in a text without rescanning it.
Searching a 10-megabyte log for a 20-character string looks trivial, yet the obvious method can make 200 million character comparisons on a bad input. Three ideas bring it down to linear time: compare fingerprints instead of characters, never re-read the text, and reuse stretches of text already known to match the pattern.
What you’ll learn
- Analyze naive matching, name its waste, and count its comparisons on its worst input.
- Implement Rabin–Karp with a rolling hash, and bound its expected running time when the base is random.
- Compute the prefix function in with an amortized argument, and use it for KMP search with at most comparisons.
- Compute the Z-function with its box, and find occurrences with .
- Recognize matching, period and border problems, and avoid the classic bugs.
The naive algorithm and its waste
Pattern matching asks for every position where a pattern of length occurs in a text of length : every shift with , a half-open range. The naive algorithm tries each shift and compares characters left to right until the first mismatch.
def naive_search(t, p):
n, m = len(t), len(p)
out = []
for s in range(n - m + 1): # every shift
j = 0
while j < m and t[s + j] == p[j]:
j += 1
if j == m:
out.append(s)
return outOn random text it is fast: most shifts fail at the first or second character. Its worst case is and . Every shift matches characters before failing on the last, so the algorithm makes comparisons, .
The waste is forgetting. After matching at shift , the algorithm knows the next characters of the text, yet at shift it reads of them again. Every linear-time algorithm below keeps and reuses that knowledge.
Rabin–Karp: compare fingerprints
Rabin–Karp (Karp & Rabin, 1987) compares a short fingerprint of each window with the pattern's fingerprint, and checks characters only when they agree. The fingerprint is a polynomial hash modulo a prime :
It is a rolling hash: sliding the window by one drops the leading character's term, shifts the rest by one power of and adds the new character, all in :
import random
def rabin_karp(t, p, mod=(1 << 61) - 1):
n, m = len(t), len(p)
if m > n:
return []
b = random.randrange(256, mod) # random base: no input is bad for every b
hp = ht = 0
for i in range(m):
hp = (hp * b + ord(p[i])) % mod
ht = (ht * b + ord(t[i])) % mod
top = pow(b, m - 1, mod) # weight of the character that leaves
out = []
for s in range(n - m + 1):
if ht == hp and t[s:s + m] == p: # verify, so every answer is right
out.append(s)
if s + m < n: # roll: drop t[s], append t[s + m]
ht = ((ht - ord(t[s]) * top) * b + ord(t[s + m])) % mod
return outExpected time. For a window , the difference is a nonzero polynomial in of degree at most over the field , so at most of the possible bases make it vanish: a spurious hit has probability at most . With , spurious hits are essentially never seen, and the expected time is , where counts the occurrences, each verified in .
Worst case. If the pattern occurs everywhere (, ), verification alone costs . Skipping verification gives a Monte Carlo algorithm in that errs with probability at most .
KMP: never move backward in the text
Suppose characters of the pattern have matched, , and then . The last characters of the text are now known: they are . Which shorter prefix of could still be aligned so that it ends at ? Exactly the prefixes of that are also suffixes of it. Knuth, Morris and Pratt (1977) precompute the longest one, for every , from the pattern alone.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| a | b | a | b | a | c | a | |
| 0 | 0 | 1 | 2 | 3 | 0 | 1 |
def prefix_function(p):
pi = [0] * len(p)
k = 0 # length of the current border
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1] # fall back to the next shorter border
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def kmp_search(t, p):
pi, q, out = prefix_function(p), 0, []
for i, c in enumerate(t): # i only moves forward
while q > 0 and c != p[q]:
q = pi[q - 1]
if c == p[q]:
q += 1
if q == len(p): # p ends at position i
out.append(i - len(p) + 1)
q = pi[q - 1]
return outInvariant. After reading , is the length of the longest prefix of that ends at position of the text (ranges half-open):
The border chain. If ends at position , the shorter prefixes that also end there are exactly its borders: , then , and so on down to 0, because a border of a border is a border. The fallback loop tries these lengths from longest to shortest and stops at the first that extends by , so it never skips a candidate (after a full match, treat as matching no character):
Amortized cost. rises by at most 1 per text character, every fallback lowers it by at least 1, and . So the fallbacks number at most in total, and each character costs one comparison plus its fallbacks:
Building .
prefix_functionis the same automaton run on the pattern against itself, so the same potential argument gives . In total, in the worst case:
What is the prefix function of ?
Show the answer
C.
: the prefix has border but not , so 2. : ends with , which is also its prefix, so 3. The fallback from at is where KMP earns its keep: , so drops to , and then matches.
The Z-function
def z_function(s):
n = len(s)
z = [0] * n
l = r = 0 # box [l, r): s[l:r] == s[:r - l]
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l]) # reuse what the box already knows
while i + z[i] < n and s[z[i]] == s[i + z[i]]:
z[i] += 1 # extend past the box by comparing
if i + z[i] > r:
l, r = i, i + z[i]
return z
def z_search(t, p, sep='\x00'): # sep must occur in neither string
z, m = z_function(p + sep + t), len(p)
return [i - m - 1 for i in range(m + 1, len(z)) if z[i] == m]The box. Keep the match that reaches farthest right among those found so far. It is a copy of a prefix:
Inside the box, copy. For , the text equals , whose match with the prefix is already known. So the match at is at least the match at , cut off at the box's edge, and exactly that when :
Outside, extend. Characters are compared explicitly only at positions . Every successful comparison moves one step right when the box is updated, and never moves left, so there are at most of them, plus at most one failed comparison per :
To find in , compute the Z-function of , where the separator occurs in neither string. It caps every Z value at , and for a position in the text part marks an occurrence at shift . The prefix function and the Z-function carry the same information about how the string overlaps itself (each can be computed from the other in linear time); pick whichever makes your problem simpler.
Boyer–Moore, and what your library does
Boyer–Moore (Boyer & Moore, 1977) aligns the pattern but compares it right to left. On a mismatch it shifts using the text character that failed (the "bad character" rule) and the suffix already matched (the "good suffix" rule), often by nearly positions. With a long pattern over a large alphabet, it examines only a small fraction of the text: sublinear on average. GNU grep searches for fixed strings with a Boyer–Moore variant (Haertel, 2010). The plain algorithm can take time when the pattern occurs very often; Galil's rule restores a linear worst case.
No algorithm can be sublinear in the worst case: Rivest (1977) proved that any algorithm must examine at least characters of the text on some inputs.
| Library call | What it does (as of 2025) | Worst case |
|---|---|---|
Python str.find, in | a Horspool-style skip search; since Python 3.10 it switches to the Two-Way algorithm (Crochemore & Perrin, 1991) for long patterns, to avoid quadratic behavior | no longer quadratic |
glibc strstr, memmem | a Horspool variant for short needles, Two-Way for needles over 256 bytes | linear |
C++ std::string::find | unspecified by the standard; common implementations scan for the first character, then compare |
std::boyer_moore_searcher for std::search. When inputs can be adversarial, as in contests, write KMP or the Z-algorithm yourself rather than trusting a quadratic library call.Recognizing it
Signals in a problem statement:
- Find, count or locate a fixed pattern in a long text, with and up to : an loop is too slow, so use KMP, the Z-function or Rabin–Karp.
- Periods, repetitions, borders: "is the string a repetition of a block?", "longest prefix that is also a suffix", "shortest string whose repetition contains ". These are prefix-function questions.
- Comparing many substrings of one string: hashing, or suffix structures.
| Problem | Key idea | Complexity |
|---|---|---|
| All occurrences of one pattern in a text | KMP, or the Z-function of | |
| Is a repetition of a shorter block? | ; yes iff and divides | |
| Is a rotation of ? | and occurs in | |
| Fewest characters to add in front of to make a palindrome | The longest palindromic prefix is the last prefix-function value of | |
| How often does each prefix of occur in ? | Count prefix-function values, then push the counts down the border chains |
Common bugs:
- Falling back once (
if) instead of repeatedly (while) in the prefix-function loop. - Mixing up for the prefix ending at with indexed by prefix length; after a full match, continue from , not from 0.
- A separator that can occur in the input, letting Z values run across it.
- In C++ Rabin–Karp: a negative value after subtracting the leaving character (add the modulus before reducing), and overflow of 64-bit products (use a 128-bit product or a Mersenne-prime reduction).
- A fixed, published base and modulus: in contests, other contestants can build colliding inputs (see Polynomial Hashing in Depth).
You must decide whether a string of length up to is a cyclic rotation of a string of the same length. Which approach fits?
- Compare the sorted characters of and
- Try all rotations of and compare each with
- Search for in with KMP or the Z-function
- Compare the character counts of and with a hash map
Show the answer
C. Search for in with KMP or the Z-function
Every rotation of is a length- window of , and every such window is a rotation, so is a rotation exactly when it occurs in . Linear-time matching makes it .
Key takeaways
- Naive matching is in the worst case, comparisons on against , because it forgets what it has read; every linear algorithm reuses that knowledge.
- Rabin–Karp rolls a polynomial hash in per shift; with a random base modulo a large prime, spurious hits have probability at most each, and the expected time is .
- KMP's prefix function, = the longest border of , takes to build and drives a search with at most comparisons that never moves backward in the text.
- The Z-function gives, for every position, the longest match with the string's prefix, in through the box; matching is the Z-function of .
- Borders are periods in disguise: the shortest period of is , and rotations, repetitions and palindromic prefixes all reduce to a prefix-function or Z computation.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How many character comparisons does naive matching make for in ?
Show the answer
D.
There are shifts, and at each one the first characters match and the last comparison fails: comparisons per shift.
Rabin–Karp, with a random base modulo and character-by-character verification, searches for in . What is its running time?
- , because spurious hits are improbable
- , because every one of the windows is a true occurrence and is verified
- It may report wrong positions
Show the answer
B. , because every one of the windows is a true occurrence and is verified
The expected time is . Here , so verification dominates. KMP and the Z-algorithm stay on every input, including this one.
A string of length 10 has . Which statement is true?
- Its shortest period is 4, and is not a power of a shorter string
- Its shortest period is 6
- Its shortest period is 4, so
- has no period shorter than 10
Show the answer
A. Its shortest period is 4, and is not a power of a shorter string
A border of length is the same thing as a period , so the longest border 6 gives the shortest period , as in . Since 4 does not divide 10, is not a repetition of a shorter block. The Optimal lesson proves, with the Fine–Wilf periodicity lemma, that a power's shortest root always has length .
The Z-algorithm reaches position inside its box , and . What is ?
- Unknown: it must be computed by comparing characters from scratch
- Exactly
Show the answer
C. Exactly
Since , the text from up to is a copy of the text from up to . The match at ends with a mismatch strictly inside that copy, so the same mismatch happens at , and : no character needs to be compared at all (the code above makes one comparison that fails, Gusfield's version skips it).
Go deeper
- The Prefix Function & Z-Function in Depth · Failure links, string periods and matching automata.
- Polynomial Hashing in Depth · Collision probabilities, double hashing and comparing substrings in O(1).
- Palindromes: Manacher’s Algorithm & the Eertree · Every palindromic substring in linear time.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 32.
- D. E. Knuth, J. H. Morris & V. R. Pratt, "Fast pattern matching in strings," SIAM Journal on Computing 6(2) (1977), 323–350.
- R. M. Karp & M. O. Rabin, "Efficient randomized pattern-matching algorithms," IBM Journal of Research and Development 31(2) (1987), 249–260.
- D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997).