Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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 (n−m+1) m(n-m+1)\,m 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 O(m)O(m) with an amortized argument, and use it for KMP search with at most 2n2n comparisons.
  • Compute the Z-function with its [l,r)[l, r) box, and find occurrences with p+#+tp + \texttt{\#} + t.
  • 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 pp of length mm occurs in a text tt of length nn: every shift ss with t[s..s+m)=pt[s..s+m) = p, a half-open range. The naive algorithm tries each shift s=0,…,n−ms = 0, \dots, n-m and compares characters left to right until the first mismatch.

python
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 out

On random text it is fast: most shifts fail at the first or second character. Its worst case is t=ant = \texttt{a}^n and p=am−1bp = \texttt{a}^{m-1}\texttt{b}. Every shift matches m−1m-1 characters before failing on the last, so the algorithm makes (n−m+1) m(n-m+1)\,m comparisons, Θ(nm)\Theta(nm).

The waste is forgetting. After matching am−1\texttt{a}^{m-1} at shift ss, the algorithm knows the next m−1m-1 characters of the text, yet at shift s+1s+1 it reads m−2m-2 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 PP:

H(x0x1⋯xm−1)=(∑i=0m−1xi b m−1−i) mod P.H(x_0 x_1 \cdots x_{m-1}) = \Big(\sum_{i=0}^{m-1} x_i\, b^{\,m-1-i}\Big) \bmod P.

It is a rolling hash: sliding the window by one drops the leading character's term, shifts the rest by one power of bb and adds the new character, all in O(1)O(1):

H(t[s+1..s+m+1))=((H(t[s..s+m))−t[s] b m−1) b+t[s+m]) mod PH\big(t[s+1..s+m+1)\big) = \Big(\big(H(t[s..s+m)) - t[s]\, b^{\,m-1}\big)\, b + t[s+m]\Big) \bmod P
Precompute bm−1 mod Pb^{m-1} \bmod P once. Each window then costs a subtraction, a multiplication and an addition.
python
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 out

Expected time. For a window w≠pw \ne p, the difference H(w)−H(p)H(w) - H(p) is a nonzero polynomial in bb of degree at most m−1m - 1 over the field ZP\Z_P, so at most m−1m-1 of the PP possible bases make it vanish: a spurious hit has probability at most (m−1)/P(m-1)/P. With P=261−1P = 2^{61}-1, spurious hits are essentially never seen, and the expected time is O(n+m+m⋅occ)O(n + m + m \cdot \mathrm{occ}), where occ\mathrm{occ} counts the occurrences, each verified in O(m)O(m).

Worst case. If the pattern occurs everywhere (t=ant = \texttt{a}^n, p=amp = \texttt{a}^m), verification alone costs Θ(nm)\Theta(nm). Skipping verification gives a Monte Carlo algorithm in O(n+m)O(n + m) that errs with probability at most n(m−1)/Pn(m-1)/P.

KMP: never move backward in the text

Suppose qq characters of the pattern have matched, p[0..q)=t[i−q..i)p[0..q) = t[i-q..i), and then t[i]≠p[q]t[i] \ne p[q]. The last qq characters of the text are now known: they are p[0..q)p[0..q). Which shorter prefix of pp could still be aligned so that it ends at t[i−1]t[i-1]? Exactly the prefixes of p[0..q)p[0..q) that are also suffixes of it. Knuth, Morris and Pratt (1977) precompute the longest one, for every qq, from the pattern alone.

ii0123456
p[i]p[i]ababaca
π[i]\pi[i]0012301
For p=ababacap = \texttt{ababaca}: π[4]=3\pi[4] = 3 because aba\texttt{aba} is both a prefix and a suffix of ababa\texttt{ababa}; at i=5i = 5 the c\texttt{c} breaks every border.
python
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 out
DerivationCorrectness and the 2n bound
  1. qi=max⁡{ q≤m:p[0..q)=t[i−q+1..i+1) }q_i = \max\{\, q \le m : p[0..q) = t[i-q+1..i+1) \,\}

    Invariant. After reading t[i]t[i], qq is the length of the longest prefix of pp that ends at position ii of the text (ranges half-open):

  2. qi=1+max⁡{ ℓ∈{qi−1, π[qi−1−1], …, 0}:p[ℓ]=t[i] }(or 0)q_i = 1 + \max\{\, \ell \in \{q_{i-1},\ \pi[q_{i-1}-1],\ \dots,\ 0\} : p[\ell] = t[i] \,\}\quad (\text{or } 0)

    The border chain. If p[0..q)p[0..q) ends at position i−1i-1, the shorter prefixes that also end there are exactly its borders: π[q−1]\pi[q-1], then π[π[q−1]−1]\pi[\pi[q-1]-1], 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 t[i]t[i], so it never skips a candidate (after a full match, treat p[m]p[m] as matching no character):

  3. #comparisons ≤ n+#fallbacks ≤ 2n\#\text{comparisons} \ \le\ n + \#\text{fallbacks} \ \le\ 2n

    Amortized cost. qq rises by at most 1 per text character, every fallback lowers it by at least 1, and q≥0q \ge 0. So the fallbacks number at most nn in total, and each character costs one comparison plus its fallbacks:

  4. T(n,m)=O(n+m)T(n, m) = O(n + m)

    Building π\pi. prefix_function is the same automaton run on the pattern against itself, so the same potential argument gives O(m)O(m). In total, in the worst case:

Check your understanding

What is the prefix function of p=aabaaabp = \texttt{aabaaab}?

  1. [0,1,0,1,2,3,4][0, 1, 0, 1, 2, 3, 4]
  2. [0,1,0,0,1,2,3][0, 1, 0, 0, 1, 2, 3]
  3. [0,1,0,1,2,2,3][0, 1, 0, 1, 2, 2, 3]
  4. [0,0,0,1,2,2,3][0, 0, 0, 1, 2, 2, 3]
Show the answer

C. [0,1,0,1,2,2,3][0, 1, 0, 1, 2, 2, 3]

π[5]\pi[5]: the prefix aabaaa\texttt{aabaaa} has border aa\texttt{aa} but not aab\texttt{aab}, so 2. π[6]\pi[6]: aabaaab\texttt{aabaaab} ends with aab\texttt{aab}, which is also its prefix, so 3. The fallback from k=2k = 2 at i=5i = 5 is where KMP earns its keep: p[2]=b≠ap[2] = \texttt{b} \ne \texttt{a}, so kk drops to π[1]=1\pi[1] = 1, and then p[1]=ap[1] = \texttt{a} matches.

The Z-function

python
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]
DerivationWhy the Z-algorithm is linear
  1. s[l..r)=s[0..r−l)s[l..r) = s[0..r-l)

    The box. Keep the match [l,r)[l, r) that reaches farthest right among those found so far. It is a copy of a prefix:

  2. Z[i] ≥ min⁡(r−i, Z[i−l])Z[i] \ \ge\ \min\big(r - i,\ Z[i-l]\big)

    Inside the box, copy. For l<i<rl < i < r, the text s[i..r)s[i..r) equals s[i−l..r−l)s[i-l..r-l), whose match with the prefix is already known. So the match at ii is at least the match at i−li - l, cut off at the box's edge, and exactly that when Z[i−l]<r−iZ[i-l] < r - i:

  3. #comparisons ≤ 2n\#\text{comparisons} \ \le\ 2n

    Outside, extend. Characters are compared explicitly only at positions i+Z[i]≥ri + Z[i] \ge r. Every successful comparison moves rr one step right when the box is updated, and rr never moves left, so there are at most nn of them, plus at most one failed comparison per ii:

To find pp in tt, compute the Z-function of p+#+tp + \texttt{\#} + t, where the separator occurs in neither string. It caps every Z value at mm, and Z[i]=mZ[i] = m for a position ii in the text part marks an occurrence at shift i−m−1i - m - 1. 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 mm 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 Θ(nm)\Theta(nm) 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 n−m+1n - m + 1 characters of the text on some inputs.

Library callWhat it does (as of 2025)Worst case
Python str.find, ina Horspool-style skip search; since Python 3.10 it switches to the Two-Way algorithm (Crochemore & Perrin, 1991) for long patterns, to avoid quadratic behaviorno longer quadratic
glibc strstr, memmema Horspool variant for short needles, Two-Way for needles over 256 byteslinear
C++ std::string::findunspecified by the standard; common implementations scan for the first character, then compareO(nm)O(nm)
C++17 adds 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 nn and mm up to 10610^6: an O(nm)O(nm) 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 ss". These are prefix-function questions.
  • Comparing many substrings of one string: hashing, or suffix structures.
ProblemKey ideaComplexity
All occurrences of one pattern in a textKMP, or the Z-function of p+#+tp + \texttt{\#} + tO(n+m)O(n + m)
Is ss a repetition uku^k of a shorter block?d=n−π[n−1]d = n - \pi[n-1]; yes iff d<nd < n and dd divides nnO(n)O(n)
Is bb a rotation of aa?∣a∣=∣b∣\abs a = \abs b and bb occurs in a+aa + aO(n)O(n)
Fewest characters to add in front of ss to make a palindromeThe longest palindromic prefix is the last prefix-function value of s+#+reverse⁡(s)s + \texttt{\#} + \operatorname{reverse}(s)O(n)O(n)
How often does each prefix of ss occur in ss?Count prefix-function values, then push the counts down the border chainsO(n)O(n)
For s=aacecaaas = \texttt{aacecaaa}, the last value is 7: the palindrome aacecaa\texttt{aacecaa} is a prefix, so adding one a\texttt{a} in front suffices.

Common bugs:

  • Falling back once (if) instead of repeatedly (while) in the prefix-function loop.
  • Mixing up π[i]\pi[i] for the prefix ending at ii with π\pi indexed by prefix length; after a full match, continue from q=π[m−1]q = \pi[m-1], 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).
Check your understanding

You must decide whether a string bb of length up to 10610^6 is a cyclic rotation of a string aa of the same length. Which approach fits?

  1. Compare the sorted characters of aa and bb
  2. Try all nn rotations of aa and compare each with bb
  3. Search for bb in a+aa + a with KMP or the Z-function
  4. Compare the character counts of aa and bb with a hash map
Show the answer

C. Search for bb in a+aa + a with KMP or the Z-function

Every rotation of aa is a length-nn window of a+aa + a, and every such window is a rotation, so bb is a rotation exactly when it occurs in a+aa + a. Linear-time matching makes it O(n)O(n).

Key takeaways

  • Naive matching is Θ(nm)\Theta(nm) in the worst case, (n−m+1) m(n-m+1)\,m comparisons on an\texttt{a}^n against am−1b\texttt{a}^{m-1}\texttt{b}, because it forgets what it has read; every linear algorithm reuses that knowledge.
  • Rabin–Karp rolls a polynomial hash in O(1)O(1) per shift; with a random base modulo a large prime, spurious hits have probability at most (m−1)/P(m-1)/P each, and the expected time is O(n+m+m⋅occ)O(n + m + m\cdot\mathrm{occ}).
  • KMP's prefix function, π[i]\pi[i] = the longest border of p[0..i]p[0..i], takes O(m)O(m) to build and drives a search with at most 2n2n comparisons that never moves backward in the text.
  • The Z-function gives, for every position, the longest match with the string's prefix, in O(n)O(n) through the [l,r)[l, r) box; matching is the Z-function of p+#+tp + \texttt{\#} + t.
  • Borders are periods in disguise: the shortest period of ss is n−π[n−1]n - \pi[n-1], 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.

Question 1

How many character comparisons does naive matching make for p=am−1bp = \texttt{a}^{m-1}\texttt{b} in t=ant = \texttt{a}^n?

  1. nn
  2. n+mn + m
  3. nm/2nm/2
  4. (n−m+1) m(n - m + 1)\,m
Show the answer

D. (n−m+1) m(n - m + 1)\,m

There are n−m+1n - m + 1 shifts, and at each one the first m−1m - 1 characters match and the last comparison fails: mm comparisons per shift.

Question 2

Rabin–Karp, with a random base modulo 261−12^{61}-1 and character-by-character verification, searches for p=amp = \texttt{a}^m in t=ant = \texttt{a}^n. What is its running time?

  1. O(n+m)O(n + m), because spurious hits are improbable
  2. Θ(nm)\Theta(nm), because every one of the n−m+1n - m + 1 windows is a true occurrence and is verified
  3. O(nlog⁡m)O(n \log m)
  4. It may report wrong positions
Show the answer

B. Θ(nm)\Theta(nm), because every one of the n−m+1n - m + 1 windows is a true occurrence and is verified

The expected time is O(n+m+m⋅occ)O(n + m + m \cdot \mathrm{occ}). Here occ=n−m+1\mathrm{occ} = n - m + 1, so verification dominates. KMP and the Z-algorithm stay O(n+m)O(n + m) on every input, including this one.

Question 3

A string ss of length 10 has π[9]=6\pi[9] = 6. Which statement is true?

  1. Its shortest period is 4, and ss is not a power uku^k of a shorter string
  2. Its shortest period is 6
  3. Its shortest period is 4, so s=u10/4s = u^{10/4}
  4. ss has no period shorter than 10
Show the answer

A. Its shortest period is 4, and ss is not a power uku^k of a shorter string

A border of length bb is the same thing as a period n−bn - b, so the longest border 6 gives the shortest period 10−6=410 - 6 = 4, as in abcdabcdab\texttt{abcdabcdab}. Since 4 does not divide 10, ss 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 n−π[n−1]n - \pi[n-1].

Question 4

The Z-algorithm reaches position ii inside its box [l,r)[l, r), and Z[i−l]<r−iZ[i - l] < r - i. What is Z[i]Z[i]?

  1. Unknown: it must be computed by comparing characters from scratch
  2. r−ir - i
  3. Exactly Z[i−l]Z[i - l]
  4. Z[i−l]+1Z[i - l] + 1
Show the answer

C. Exactly Z[i−l]Z[i - l]

Since s[l..r)=s[0..r−l)s[l..r) = s[0..r-l), the text from ii up to rr is a copy of the text from i−li - l up to r−lr - l. The match at i−li - l ends with a mismatch strictly inside that copy, so the same mismatch happens at ii, and Z[i]=Z[i−l]Z[i] = Z[i-l]: no character needs to be compared at all (the code above makes one comparison that fails, Gusfield's version skips it).

Go deeper

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