Sub topic 1
The Problem: Why Naive Substring Search Is Slow
Substring search asks a simple question: where does a pattern of length m appear inside a text of length n? Editors, grep, DNA tools, and plagiarism checkers all answer it constantly. This chapter shows the obvious algorithm, measures how much work it does, and finds the input that makes it slow. Later chapters use that weakness to motivate rolling hashes.
Prerequisites
This chapter assumes you can:
- Write loops and functions in Python or a similar language.
- Index and slice strings, for example
s[i:i + m]. - Read Big-O notation such as O(n) and O(nm).
You do not need to know anything about hashing yet.
The naive algorithm
The naive approach tries every possible starting position in the text. At each position it compares the pattern to the text one character at a time and stops at the first mismatch. A text of length n has n − m + 1 starting positions.
def naive_search(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("abracadabra", "abra")) # ([0, 7], 17)On ordinary English text, most windows fail on the first or second character, so the inner loop is usually short. That makes the algorithm look fast in casual testing.
Where the time goes
The cost depends on how far each comparison gets before it hits a mismatch. Suppose the text is "aaaa...a" and the pattern is "aaab". Every window matches the first m − 1 characters and fails only on the last one. Each of the n − m + 1 windows then costs m comparisons.
for n in (1_000, 2_000, 4_000):
text = "a" * n
pattern = "a" * 99 + "b" # m = 100
_, c = naive_search(text, pattern)
print(n, c)
# 1000 90100
# 2000 190100
# 4000 390100The total is (n − m + 1) · m, which is O(nm). With n = 10⁶ and m = 10³ that comes to about a billion character comparisons, even though the answer is "no matches".
The real waste
When the window moves from position i to i + 1, it shares m − 1 characters with the previous window. The naive algorithm ignores this overlap and starts over from scratch. The fix this tutorial builds is to compress each window into a single number, a hash. We compare numbers instead of strings, and we update the number in O(1) when the window slides rather than recomputing it.
| Input kind | Naive cost | Why |
|---|---|---|
| Random text, random pattern | about O(n) | mismatches happen almost immediately |
| Highly repetitive text and pattern | O(nm) | almost every window nearly matches |
| Pattern longer than text | O(1) | no windows to check |
Exercise
For text = "a" * 20 and pattern = "aab", how many character comparisons does naive_search make, and why?
Show answer
There are 20 − 3 + 1 = 18 windows. Each window matches "a", then fails on the third character, because the text has 'a' where the pattern has 'b'. Each window therefore costs 3 comparisons, for a total of 18 × 3 = 54.
Exercise
Give a pattern of length 4 that makes the naive search do only about n comparisons on the text "a" * n.
Show answer
Any pattern that starts with a character other than 'a', such as "baaa". Every window fails on the first comparison, so the total is n − 3 comparisons.