Sub topic 9
Finding a substring: the naive approach
This chapter assumes you can read basic Python, know zero-based indexing and slicing, and have met Big-O notation. Earlier chapters covered indexing, slicing, and string comparison. Substring search builds directly on them.
The problem
Substring search asks where a short string, the pattern, first appears inside a longer string, the text. The answer is the starting index, or a sentinel such as -1 if the pattern is absent. Python's str.find, Java's indexOf, and C's strstr all solve this problem.
Use n for the length of the text and m for the length of the pattern.
The naive algorithm
The naive approach tries every possible starting position, called an alignment. At each one it checks whether the pattern matches the text that begins there.
def find(text, pattern):
n, m = len(text), len(pattern)
for i in range(n - m + 1):
if text[i:i + m] == pattern:
return i
return -1
print(find("abracadabra", "cad")) # 4
print(find("abracadabra", "xyz")) # -1The loop stops at n - m because a pattern that starts later would run past the end of the text. Each alignment slices m characters and compares them with the pattern.
What it costs
A comparison stops at the first mismatch, so the cost per alignment depends on the data. There are n - m + 1 alignments. The slice also copies m characters before the comparison starts, so each alignment costs at least O(m) in this version.
| Case | Example | Work |
|---|---|---|
| Best | The first character of the pattern rarely matches | About `n` character comparisons |
| Worst | Long partial matches that fail at the end | About `n * m` character comparisons |
The worst case needs repetitive text. A pattern such as "aaaab" searched in "aaaaaaaaaa..." matches four characters at every alignment and then fails on the fifth. Ordinary prose is closer to the best case, which is why naive search often performs acceptably in practice.
Counting the work
The slice version hides the character comparisons. This version makes them explicit and counts them.
def find_counting(text, pattern):
comparisons = 0
for i in range(len(text) - len(pattern) + 1):
j = 0
while j < len(pattern):
comparisons += 1
if text[i + j] != pattern[j]:
break
j += 1
else:
return i, comparisons
return -1, comparisons
print(find_counting("a" * 20, "xyz")) # (-1, 18)
print(find_counting("a" * 20, "aaaab")) # (-1, 80)Both searches fail. The first checks 18 alignments and spends one comparison on each. The second checks 16 alignments and spends 5 on each, so the work is 80 comparisons, which is the n * m shape. Doubling the text and the pattern roughly quadruples that count.
Common errors
- Off-by-one in the loop bound. Using
range(n - m)skips the last alignment, so a pattern at the very end of the text is never found. Test with the pattern at the start, at the end, and equal to the whole text. - Pattern longer than the text.
n - m + 1is then zero or negative,rangeis empty, and the function returns-1. This is correct, but only because the bound was computed first. Do not index into the text before checking it. - Empty pattern. Here
mis 0, and the slicetext[0:0]equals"", so the function returns0. That matches Python's"abc".find(""). Decide deliberately whether your own code should allow it. - Assuming a fixed cost per slice. A slice allocates and copies. A hot loop that slices at every alignment spends time on copying as well as comparing. Languages with cheap views or
startswith(pattern, i)avoid the copy. - Mixing units. Indices count code points in Python but bytes in other languages. If you search encoded bytes, the returned index is a byte offset, not a character position.
Why this matters next
The naive method throws away information. After a mismatch at alignment i, it moves to i + 1 and re-reads characters it has already compared. The next chapter shows how KMP and Rabin-Karp avoid that repeated work.
Exercise
Using find_counting, how many character comparisons does it make when searching for "aab" in "aaaaaa"? Explain your count.
Show answer
There are 6 - 3 + 1 = 4 alignments. At each one the first two characters match ("a", "a") and the third fails ("a" against "b"), so each alignment costs 3 comparisons. The total is 4 * 3 = 12, and the function returns (-1, 12).
Exercise
A search loop is written as for i in range(n - m). Which input exposes the bug, and what does the function return?
Show answer
Any input where the pattern occurs only at the very end, such as text "abcde" and pattern "de". The last valid alignment is i = 3, but range(5 - 2) stops at 2, so the function returns -1 instead of 3.