TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › The Naive String-Matching Algorithm

The Naive String-Matching Algorithm

Find every occurrence of a word in a document, a gene in a chromosome, a signature in network traffic: string matching is one of the most frequently executed algorithmic tasks. This section develops four algorithms for it. They all solve the same problem, and they differ in how much they learn from each comparison. The simplest, the naive algorithm, learns nothing; its worst case of Θ(nm)\Theta(nm) comparisons is the benchmark the others improve on.

The problem

The text is an array T[0..n−1]T[0..n-1] and the pattern an array P[0..m−1]P[0..m-1] of characters from a finite alphabet Σ\Sigma, with m≤nm \le n. The pattern occurs with shift ss in the text if

T[s+j]=P[j]for j=0,1,…,m−1,0≤s≤n−m.T[s + j] = P[j] \quad \text{for } j = 0, 1, \ldots, m - 1, \qquad 0 \le s \le n - m .

Such an ss is a valid shift; the string-matching problem asks for all of them. Some vocabulary: a string ww is a prefix of xx if x=wyx = wy for some string yy, and a suffix if x=ywx = yw; PqP_q denotes the prefix P[0..q−1]P[0..q-1] of length qq, so P0P_0 is the empty string and Pm=PP_m = P. Comparing two strings of length kk character by character takes Θ(k)\Theta(k) time in the worst case, but stops at the first mismatch.

The algorithm

Try every shift and compare the pattern with the window of the text:

text
NAIVE-MATCH(T, P)
1  n = len(T); m = len(P)
2  for s = 0 to n - m
3      j = 0
4      while j < m and T[s + j] == P[j]
5          j = j + 1
6      if j == m
7          report s

The program prints every shift with the number of character comparisons it used.

python · try it yourself
def naive_match(T, P, verbose=False):
    n, m, comparisons, found = len(T), len(P), 0, []
    for s in range(n - m + 1):
        j = 0
        while j < m:
            comparisons += 1
            if T[s + j] != P[j]:
                break
            j += 1
        if verbose:
            print(f"  shift {s:2}: matched {j} of {m}" + ("  <- match" if j == m else ""))
        if j == m:
            found.append(s)
    return found, comparisons

found, comps = naive_match("acaabcabaabcab", "abcab", verbose=True)
print("matches at", found, "with", comps, "comparisons")
  shift  0: matched 1 of 5
  shift  1: matched 0 of 5
  shift  2: matched 1 of 5
  shift  3: matched 5 of 5  <- match
  shift  4: matched 0 of 5
  shift  5: matched 0 of 5
  shift  6: matched 2 of 5
  shift  7: matched 0 of 5
  shift  8: matched 1 of 5
  shift  9: matched 5 of 5  <- match
matches at [3, 9] with 23 comparisons

Most shifts fail on the first or second letter, which is typical for natural text: the naive algorithm is often fast in practice, and simple versions of it (with a fast first-character scan) are what many standard libraries use for short patterns.

The worst case

Each shift costs at most mm comparisons, and there are n−m+1n - m + 1 shifts, so the running time is O((n−m+1)m)O((n - m + 1)m). The bound is tight: for T=anT = a^n and P=am−1bP = a^{m-1}b, every shift matches m−1m - 1 letters before failing on the last one, so exactly (n−m+1)m(n - m + 1)m comparisons are made. With m=n/2m = n/2 that is Θ(n2)\Theta(n^2). The text ana^n and the pattern ama^m are just as bad, with every shift valid.

python · try it yourself
def naive_comparisons(T, P):
    n, m, c = len(T), len(P), 0
    for s in range(n - m + 1):
        for j in range(m):
            c += 1
            if T[s + j] != P[j]:
                break
    return c

print("    n     m   comparisons   (n-m+1)m")
for n, m in [(100, 10), (1000, 10), (1000, 100), (1000, 500), (2000, 1000)]:
    T, P = "a" * n, "a" * (m - 1) + "b"
    print(f"{n:5} {m:5} {naive_comparisons(T, P):13} {(n - m + 1) * m:10}")
    n     m   comparisons   (n-m+1)m
  100    10           910        910
 1000    10          9910       9910
 1000   100         90100      90100
 1000   500        250500     250500
 2000  1000       1001000    1001000

The weakness is plain from the trace: after matching m−1m - 1 letters at shift ss, the algorithm knows T[s..s+m−2]T[s..s+m-2] exactly, yet at shift s+1s + 1 it compares those letters again. KMP and the automaton method keep that information (The Knuth-Morris-Pratt Algorithm, String Matching with Finite Automata) and never re-read a text character.

Random text

On random text the picture is much better. If each character is drawn uniformly from an alphabet of size d≥2d \ge 2, a comparison succeeds with probability 1/d1/d, so the expected number of comparisons at one shift is

1+1d+1d2+⋯+1dm−1<11−1/d=dd−1≤2.1 + \frac{1}{d} + \frac{1}{d^2} + \cdots + \frac{1}{d^{m-1}} < \frac{1}{1 - 1/d} = \frac{d}{d - 1} \le 2 .

Over all shifts that is fewer than 2(n−m+1)2(n - m + 1) comparisons, linear in nn whatever the pattern. The program measures it on random texts over alphabets of size 2 and 4 (like DNA); a single random text fluctuates slightly around the expectation.

python · try it yourself
import random

def naive_comparisons(T, P):
    n, m, c = len(T), len(P), 0
    for s in range(n - m + 1):
        for j in range(m):
            c += 1
            if T[s + j] != P[j]:
                break
    return c

rng = random.Random(4)
for alphabet in ["ab", "acgt"]:
    d = len(alphabet)
    T = "".join(rng.choice(alphabet) for _ in range(20000))
    P = "".join(rng.choice(alphabet) for _ in range(12))
    c = naive_comparisons(T, P)
    print(f"alphabet size {d}: {c / (len(T) - len(P) + 1):.3f} comparisons per shift "
          f"(expected value just below d/(d-1) = {d / (d - 1):.3f})")
alphabet size 2: 2.012 comparisons per shift (expected value just below d/(d-1) = 2.000)
alphabet size 4: 1.329 comparisons per shift (expected value just below d/(d-1) = 1.333)

Real data is not random, though. DNA has long repeats, logs repeat the same prefixes over and over, and an attacker can choose a text that triggers the worst case, so guaranteed linear time matters.

In C++

The naive matcher in C++ on the worst-case input, counting comparisons. The standard library's std::string::find is a naive-style search too (implementations speed up the inner loop with memchr/memcmp but keep the quadratic worst case); C++17 added std::boyer_moore_searcher for long patterns.

cpp · try it yourself
#include <cstdio>
#include <string>
#include <vector>

std::vector<int> naive_match(const std::string& T, const std::string& P, long long& comparisons) {
    std::vector<int> found;
    int n = int(T.size()), m = int(P.size());
    for (int s = 0; s + m <= n; s++) {
        int j = 0;
        while (j < m) {
            comparisons++;
            if (T[s + j] != P[j]) break;
            j++;
        }
        if (j == m) found.push_back(s);
    }
    return found;
}

int main() {
    long long c = 0;
    auto found = naive_match("acaabcabaabcab", "abcab", c);
    std::printf("matches:");
    for (int s : found) std::printf(" %d", s);
    std::printf(" (%lld comparisons)\n", c);
    std::string T(4000, 'a'), P = std::string(1999, 'a') + "b";
    c = 0;
    naive_match(T, P, c);
    std::printf("worst case n = 4000, m = 2000: %lld comparisons = (n - m + 1) m = %d\n", c, 2001 * 2000);
}
matches: 3 9 (23 comparisons)
worst case n = 4000, m = 2000: 4002000 comparisons = (n - m + 1) m = 4002000

Practise a related sliding-window search with Find All Anagrams.

Test yourself

How many comparisons does the naive algorithm make for T=a10T = a^{10} and P=aabP = aab?

  1. 8
  2. 10
  3. 24
  4. 30

What is the worst-case running time of the naive algorithm?

  1. Θ(n)\Theta(n)
  2. Θ(n+m)\Theta(n + m)
  3. Θ((n−m+1)m)\Theta((n - m + 1)m)
  4. Θ(nlg⁡m)\Theta(n \lg m)

On random text over an alphabet of size d≥2d \ge 2, how many comparisons does the naive algorithm expect per shift?

  1. Fewer than d/(d−1)≤2d/(d - 1) \le 2
  2. About m/2m/2
  3. About mm
  4. About lg⁡m\lg m

What information does the naive algorithm throw away?

  1. The pattern length
  2. The letters of the text it has just matched, which it compares again at the next shift
  3. The alphabet
  4. The shifts already reported