Sub topic 1
The Problem: Why Naive Substring Search Is Slow
Substring search asks a simple question: given a long string text of length n and a shorter string pattern of length m, at which positions does pattern occur in text? Editors, grep, DNA sequence tools, plagiarism checkers, and log scanners all answer this question constantly. This chapter builds the obvious solution, measures where it spends its time, and pins down the exact inefficiency that rolling hashes remove in later chapters.
Prerequisites
This chapter assumes you are comfortable with:
- Basic programming in Python or a similar language (loops, functions, lists).
- Strings, zero-based indexing, and slicing such as
text[i:i + m]. - Big-O notation, including the difference between O(n + m) and O(nm).
- Integer division and the modulo operator
%. These are not used here but matter from the next chapter on. - The basic idea of a hash function: a function that maps a value to a number, where equal inputs always give equal outputs.
The Naive Algorithm
The naive algorithm tries every possible starting position. A window is the slice of text of length m that starts at position i. There are n − m + 1 windows. For each window, the algorithm compares the window to the pattern character by character and stops at the first mismatch.
def naive_search(text, pattern):
n, m = len(text), len(pattern)
matches = []
for i in range(n - m + 1): # every window start
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
if j == m: # all m characters matched
matches.append(i)
return matches
print(naive_search("abracadabra", "abra")) # [0, 7]
print(naive_search("aaaa", "aa")) # [0, 1, 2] (overlapping matches)
print(naive_search("abc", "abcd")) # [] (pattern longer than text)
print(naive_search("abc", "")) # [0, 1, 2, 3]The edge cases are handled by the loop bounds without special code:
- When m > n,
range(n - m + 1)is empty, so the function returns no matches. - When m = 0, the inner loop never runs,
j == mholds at once, and every position from 0 to n counts as a match. Python's own"abc".find("")returns 0 for the same reason.
Counting the Work
Wall-clock time depends on the machine and is noisy to measure. A more reliable measure is the number of character comparisons, because that number is the inner loop's cost. The function below counts comparisons. It follows the same logic as naive_search but stops at the first mismatch in each window.
import random
def count_comparisons(text, pattern):
n, m = len(text), len(pattern)
comparisons = 0
for i in range(n - m + 1):
for j in range(m):
comparisons += 1
if text[i + j] != pattern[j]:
break
return comparisons
n, m = 100_000, 100
# Worst case: every window matches until the last character.
bad_text = "a" * n
bad_pattern = "a" * (m - 1) + "b"
print(count_comparisons(bad_text, bad_pattern)) # 9990100 = (n - m + 1) * m
# Typical case: random lowercase letters.
random.seed(1)
letters = "abcdefghijklmnopqrstuvwxyz"
rand_text = "".join(random.choice(letters) for _ in range(n))
rand_pattern = "".join(random.choice(letters) for _ in range(m))
print(count_comparisons(rand_text, rand_pattern)) # roughly 104,000The two inputs have the same lengths, yet the numbers differ by a factor of almost 100.
Why random text is cheap
With random text over an alphabet of size σ, each window's first comparison succeeds with probability 1/σ. The second comparison only runs if the first succeeded, so it runs with probability 1/σ², and so on. The expected comparisons per window are 1 + 1/σ + 1/σ² + …, which is less than σ/(σ − 1). For σ = 26 that is about 1.04. The total is close to n, which is effectively linear.
Why repetitive text is expensive
In "aaaa…a" searched for "aa…ab", every window agrees with the pattern on the first m − 1 characters and fails only on the last one. Each of the n − m + 1 windows costs exactly m comparisons:
(n − m + 1) · m comparisons, which is O(nm).
When m is about n/2, this grows to about n²/4. With n = 1,000,000 and m = 500,000, that comes to 250 billion comparisons.
| Input shape | Comparisons per window | Total | Growth |
|---|---|---|---|
| Random text, large alphabet | about 1 | about n | O(n) |
| Natural English text | a few | a few times n | O(n) in practice |
| DNA (σ = 4), long shared runs | up to dozens | tens of times n | between O(n) and O(nm) |
| `aaaa…a` vs `aa…ab` | m | (n − m + 1)·m | O(nm) |
| Pattern never shares a first character | 1 | n − m + 1 | O(n) |
Repetitive inputs are common in real data: log files with long identical prefixes, genomes with repeated regions, binary files full of zero bytes. An attacker can also construct them deliberately when a service searches user-supplied strings.
Where the Waste Comes From
Adjacent windows overlap in m − 1 characters. When the algorithm moves from window i to window i + 1, it has just looked at text[i+1 .. i+m-1] and knows how those characters compared with the pattern. The naive algorithm throws that knowledge away and starts over from pattern[0].
There are two broad ways to stop re-reading the shared part:
- Reuse the comparison results. Knuth-Morris-Pratt, the Z-algorithm, and Boyer-Moore precompute facts about the pattern so they know how far they can safely shift after a mismatch. These algorithms give guaranteed linear or sublinear behavior, but their logic is specific to exact single-pattern matching.
- Summarize each window as a number. If each window had a short fingerprint, you could compare fingerprints in O(1) and check characters only when fingerprints agree. Recomputing a fingerprint from scratch costs O(m) per window, which is no improvement. The trick is a fingerprint that can be updated in O(1) when one character leaves and another enters. That updatable fingerprint is a rolling hash, and the search built on it is Rabin-Karp.
This tutorial follows the second path. It extends naturally to searching many patterns at once, comparing arbitrary substrings, and splitting files into chunks, which the comparison-reuse algorithms do not handle as easily.
Common Mistakes in Naive Search
These bugs also show up later in Rabin-Karp, because it uses the same window loop.
- Off-by-one bounds. Writing
range(n - m)skips the last window, so a match at the very end of the text is missed. The correct count is n − m + 1. - Indexing past the end. Looping over
range(n)and readingtext[i + j]raisesIndexError(or reads garbage memory in C) once i > n − m. - Losing overlapping matches. Jumping ahead by m after a match, as some
findloops do, reports only[0, 2]for"aa"in"aaaa"instead of[0, 1, 2]. Decide which behavior you want and test it explicitly. - Hiding the cost in a slice.
text[i:i + m] == patternlooks like one operation, but it copies m characters and compares up to m of them. In the worst case it is still O(nm), and the copy adds allocation cost.
Summary of the Cost Model
| Quantity | Naive search |
|---|---|
| Windows examined | n − m + 1 |
| Cost per window, best | 1 comparison |
| Cost per window, worst | m comparisons |
| Total, typical text | about n |
| Total, worst case | (n − m + 1)·m = O(nm) |
| Extra memory | O(1), plus the output list |
The next chapter introduces the modular arithmetic needed to turn a window into a small number. The chapters after that build the rolling update that cuts the cost of moving from one window's number to the next to O(1).
Exercise
For text = "a" * 20 and pattern = "aaab", how many character comparisons does count_comparisons perform? Show the formula.
Show answer
There are n − m + 1 = 20 − 4 + 1 = 17 windows. Each window matches "aaa" and then fails on "b", so it costs 4 comparisons. The total is 17 × 4 = 68.
Exercise
Change naive_search so that it returns non-overlapping matches only, scanning left to right. What does it return for ("aaaa", "aa") and for ("abababa", "aba")?
Show answer
Replace the for loop with a while loop that advances i by m after a match and by 1 otherwise: i = 0; while i <= n - m: compare; if j == m: append i and set i += m, else i += 1. The results are [0, 2] for ("aaaa", "aa") and [0, 4] for ("abababa", "aba"). The overlapping version would return [0, 1, 2] and [0, 2, 4].
Exercise
For a fixed text length n, which pattern length m maximizes the worst-case comparison count (n − m + 1)·m, and roughly what is that maximum?
Show answer
Treat f(m) = (n − m + 1)·m as a quadratic in m. It peaks at m = (n + 1)/2, giving about (n + 1)²/4 comparisons. For n = 1,000,000 that is about 2.5 × 10^11 comparisons, so the naive worst case is quadratic in n.
Exercise
Explain in one or two sentences why random text over a 26-letter alphabet costs about 1.04 comparisons per window on average.
Show answer
The k-th comparison in a window only runs if the previous k − 1 characters all matched, which happens with probability (1/26)^(k−1). Summing 1 + 1/26 + 1/26² + … gives at most 26/25 = 1.04.