Sub topic 2
Naive Search and Why It Can Be Slow
This chapter assumes you can read Python, are comfortable with zero-based string indexing, and know what O(n · m) means. We use the notation from the previous chapter: the text T has length n, the pattern P has length m, and a match at shift i means T[i:i+m] == P.
The brute-force idea
The simplest correct algorithm tries every possible starting position. A match can begin at any shift from 0 to n - m. At each shift, compare the pattern with the window of text that starts there.
def naive_search(text, pattern):
n, m = len(text), len(pattern)
return [i for i in range(n - m + 1) if text[i:i + m] == pattern]
print(naive_search("abababca", "abab")) # [0, 2]This version is short and correct, and it reports overlapping matches. The matches at shifts 0 and 2 share the characters ab. The slice comparison hides the real work, though. Python builds a new string of length m at each shift and then compares it character by character.
Counting the comparisons
To see the cost, write the inner loop out and count every character comparison.
def naive_search_count(text, pattern):
n, m = len(text), len(pattern)
matches, comparisons = [], 0
for i in range(n - m + 1):
j = 0
while j < m:
comparisons += 1
if text[i + j] != pattern[j]:
break
j += 1
if j == m:
matches.append(i)
return matches, comparisons
print(naive_search_count("abababca", "abab")) # ([0, 2], 12)
print(naive_search_count("a" * 20, "aaaab")) # ([], 80)The second call shows the worst case. The text is all a, and the pattern is aaaab. At each of the 16 shifts, the first four characters match and the fifth fails. Every shift costs the full m = 5 comparisons, so the total is 16 × 5 = 80.
The worst case in general
There are n - m + 1 shifts, and each one can cost up to m comparisons. The total is at most (n - m + 1) · m, which is O(n · m). The bound is tight: inputs like a…a against a…ab reach it.
| n | m | Worst-case comparisons |
|---|---|---|
| 1,000 | 10 | about 10,000 |
| 1,000,000 | 1,000 | about 1,000,000,000 |
| 10,000,000 | 100,000 | about 10¹² |
On ordinary text the naive method is often fast. Most shifts fail on the first or second character, so the cost is close to n. Repetitive data breaks this. DNA, log files, binary formats, and adversarial input all contain long runs of partial matches, and on that kind of data the quadratic case shows up in practice.
Where the work is wasted
Look again at the all-a example. At shift 0, the algorithm learns that T[0..3] is aaaa. Then it moves to shift 1 and compares T[1], T[2], and T[3] again, even though it already knows their values. The naive method throws away everything it learned from a partial match and moves the text pointer back.
That waste is what KMP removes. When a partial match fails, part of the matched text may already be a valid start for the next attempt. If we know, from the pattern alone, how long that part is, we can skip ahead without rereading any text character. The next chapter defines this idea precisely using borders.
Exercise
Using naivesearchcount's counting rule, how many character comparisons does naive search make for text "aaaaaa" and pattern "aab"? Which matches does it report?
Show answer
There are 6 - 3 + 1 = 4 shifts. At each one, "a" and "a" match and then "b" fails against "a", so each shift costs 3 comparisons. The total is 12 comparisons and no matches are reported.
Exercise
Give a pattern of length m and a text of length n where naive search makes only about n - m + 1 comparisons, and explain why.
Show answer
Use text "a" n and pattern "b" m. Every shift fails on its first comparison, because "b" never equals "a", so each of the n - m + 1 shifts costs exactly 1 comparison.