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 comparisons is the benchmark the others improve on.
The problem
The text is an array and the pattern an array of characters from a finite alphabet , with . The pattern occurs with shift in the text if
Such an is a valid shift; the string-matching problem asks for all of them. Some vocabulary: a string is a prefix of if for some string , and a suffix if ; denotes the prefix of length , so is the empty string and . Comparing two strings of length character by character takes 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:
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 sThe program prints every shift with the number of character comparisons it used.
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 comparisons, and there are shifts, so the running time is . The bound is tight: for and , every shift matches letters before failing on the last one, so exactly comparisons are made. With that is . The text and the pattern are just as bad, with every shift valid.
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 letters at shift , the algorithm knows exactly, yet at shift 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 , a comparison succeeds with probability , so the expected number of comparisons at one shift is
Over all shifts that is fewer than comparisons, linear in 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.
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.
#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 and ?
- 8
- 10
- 24
- 30
What is the worst-case running time of the naive algorithm?
On random text over an alphabet of size , how many comparisons does the naive algorithm expect per shift?
- Fewer than
- About
- About
- About
What information does the naive algorithm throw away?
- The pattern length
- The letters of the text it has just matched, which it compares again at the next shift
- The alphabet
- The shifts already reported