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 nested loops, and know what O(n · m) means. The previous chapter defined the problem: given a text of length n and a pattern of length m, report every index where the pattern occurs. This chapter covers the simplest algorithm that solves it, measures how much work it does, and shows which part of that work is wasted. The wasted work is what KMP removes.
The Idea: Try Every Shift
A shift is a candidate starting position i in the text. The pattern fits at shift i only if i + m <= n, so the valid shifts are 0, 1, ..., n - m. That gives n - m + 1 shifts. The naive algorithm checks each shift on its own, compares the pattern against the text window text[i:i + m], and records i if every character matches.
The shortest version in Python uses slicing:
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]The result includes both 0 and 2, so the two occurrences overlap: they share the characters ab at indices 2 and 3. The naive algorithm finds overlapping matches for free, because it tests every shift independently and never skips any.
Counting the Work
To reason about cost, write the inner comparison out by hand and count character comparisons. This version stops at the first mismatch, which the flowchart above also does:
def naive_search_counted(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_counted("abababca", "abab")) # ([0, 2], 10)
print(naive_search_counted("aaaaab", "aab")) # ([3], 12)Here is how the second call adds up to 12 comparisons. The text is aaaaab (n = 6) and the pattern is aab (m = 3):
| Shift i | Window | Comparisons | Outcome |
|---|---|---|---|
| 0 | `aaa` | 3 (a=a, a=a, a≠b) | mismatch at j = 2 |
| 1 | `aaa` | 3 | mismatch at j = 2 |
| 2 | `aaa` | 3 | mismatch at j = 2 |
| 3 | `aab` | 3 | match |
Every shift costs the full m comparisons, and there are n − m + 1 shifts. That product, (n − m + 1) · m, is the most the naive algorithm can ever do, because no shift can cost more than m.
The Worst Case
The worst case happens when almost every shift matches for a long time before failing. The standard example is a text of all as and a pattern of m - 1 as followed by one b:
def naive_comparisons(n, m):
text = "a" * n
pattern = "a" * (m - 1) + "b"
return naive_search_counted(text, pattern)[1]
for n, m in [(20, 5), (1000, 10), (1000, 500), (10000, 100)]:
print(n, m, naive_comparisons(n, m), (n - m + 1) * m)
# 20 5 80 80
# 1000 10 9910 9910
# 1000 500 250500 250500
# 10000 100 990100 990100The measured counts equal the bound exactly. The pattern "a" * m gives the same count against the same text, because every shift then matches all m characters and every shift is reported as a match.
How bad can (n − m + 1) · m get for a fixed n? The product grows with m until about m ≈ (n + 1) / 2, then shrinks again. A very short pattern has few characters to compare, and a very long one has few shifts. The peak is roughly n² / 4, so a 1 MB text with a 500 KB pattern needs on the order of 62 billion comparisons in the worst case.
The worst case is therefore Θ((n − m + 1) · m). People usually write this as O(n · m).
Best and Typical Cases
The naive algorithm is not always slow. If the first pattern character rarely appears in the text, most shifts fail on their first comparison, and the total is close to n − m + 1. Searching for "zebra" in ordinary English prose behaves like this.
Random text is also cheap on average. With an alphabet of σ equally likely characters, a shift survives each comparison with probability 1/σ, so the expected number of comparisons per shift is below 1 / (1 − 1/σ). That is at most 2 for any alphabet with two or more letters. On random data the naive algorithm runs in expected linear time.
The trouble is that real inputs are often not random. DNA has a four-letter alphabet and long repeats. Log files, machine-generated data, and binary formats contain long runs of the same byte. Anyone who controls the input can also build the bad case on purpose and use it as a denial-of-service attack against a server that does naive matching. A guaranteed bound matters in exactly these situations.
| Input shape | Comparisons | Example |
|---|---|---|
| First pattern char is rare in text | about n − m + 1 | `"zebra"` in English prose |
| Random text, alphabet size σ ≥ 2 | expected below 2(n − m + 1) | random bytes |
| Highly repetitive text and pattern | (n − m + 1) · m | `"aaa…a"` and `"aa…ab"` |
Where the Work Is Wasted
Go back to shift 0 in the aaaaab table. Before the mismatch at j = 2, the algorithm learned that text[0] == 'a' and text[1] == 'a'. At shift 1 it compares text[1] against pattern[0] again, even though it already knows text[1] is a and pattern[0] is a. The algorithm throws away everything it learned at one shift before starting the next.
You can describe the waste in terms of the text index. Suppose shift i mismatches at text[i + j] after matching j characters. The next comparison reads text[i + 1], so the text position moves back by j - 1. In the worst case each text character is read up to m times. Moving backward has a second cost: the algorithm needs random access to the text. You cannot run naive search over a stream, such as a network socket or a file read in chunks, without buffering the last m characters.
The information is not useless. After matching j characters at shift i, we know the exact contents of text[i .. i + j - 1], because they equal pattern[0 .. j - 1]. Whether a later shift can possibly succeed depends only on the pattern, not on the text. If you know ahead of time how the pattern overlaps with itself, you can decide which shifts to skip and how many characters are already matched, all without looking back at the text. Precomputing that self-overlap is what the next two chapters do with borders and the prefix function.
Gotchas in Naive Implementations
Slicing hides the cost
The slicing version text[i:i + m] == pattern builds a new string of length m at every shift before it compares anything. The comparison stops early, but the copy has already been made, so this version does Θ((n − m + 1) · m) work on every input, including the friendly ones. It is fast in practice only because the copy and compare run in C. If you need to measure or explain cost, use the explicit loop. If you need speed in real code, call str.find or the re module. CPython's search is a tuned hybrid, and since version 3.10 it uses the Crochemore–Perrin two-way algorithm for longer patterns, so it does not degrade quadratically.
Boundary inputs
range(n - m + 1) already handles two boundaries correctly. If m > n, the range is empty and no matches are reported. If m = 0, the empty pattern matches at every one of the n + 1 positions. A later chapter goes through these cases in detail and makes KMP behave the same way.
Early exit is required for the analysis
Without the break on the first mismatch, every shift costs m comparisons and the best-case and average-case results above no longer hold. The early exit is what makes the naive algorithm fast on typical data. It does nothing for the worst case.
Summary of the Cost Model
| Measure | Naive search |
|---|---|
| Worst-case comparisons | (n − m + 1) · m, at most about n²/4 |
| Best case | n − m + 1 |
| Extra space (explicit loop) | O(1) beyond the output |
| Text index moves backward? | Yes, by up to m − 1 |
| Works on a stream without buffering? | No |
| Preprocessing | None |
Naive search needs no preprocessing and has almost no constant overhead, so it is a reasonable choice for short patterns over non-adversarial data. KMP is built for the cases where you need a linear bound on every input and a text index that only moves forward.
Exercise
Using the explicit-loop naive search, how many character comparisons are made for text "a" * 12 and pattern "aaab"? Is any match reported?
Show answer
There are 12 - 4 + 1 = 9 shifts. At each shift the three a's match and the b mismatches, so each shift costs 4 comparisons. The total is 9 * 4 = 36 comparisons and no match is reported.
Exercise
For a text of length n = 21, which pattern length m maximizes the worst-case comparison count (n - m + 1) * m, and what is that maximum?
Show answer
The count is (22 - m) m, which peaks at m = 11 and gives 11 11 = 121 comparisons.
Exercise
Give a text of length 10 and a pattern of length 3 for which the explicit-loop naive search makes exactly n - m + 1 = 8 comparisons. Explain why.
Show answer
One example is text "bbbbbbbbbb" and pattern "abc". Every shift fails on its first comparison because no text character equals 'a', so each of the 8 shifts costs exactly 1 comparison.
Exercise
Naive search fails at shift i after matching j = 5 characters. Which text index does it compare next, and how far back does the text index move? What does the algorithm already know about text[i+1 .. i+4]?
Show answer
It next compares text[i + 1] with pattern[0]. The last index read was i + 5, so the text index moves back by 4. Because the first 5 characters matched, text[i+1 .. i+4] equals pattern[1 .. 4]. The algorithm could have known this without rereading the text.