Naive string search
About this lesson
Finding a word inside a text is one of the most common jobs a program does. The simplest way slides the pattern along the text one place at a time and compares it character by character. Watch it find "ABC" in "ABABCABC" with 12 comparisons, then watch a repetitive text push it to its worst case of (n − m + 1)·m. The Software lessons "Strings: text in memory" and "Searching: linear and binary" cover how strings are stored and what a linear scan is; this lesson builds on both.
Find a pattern in text
Find every place the pattern p = "ABC" occurs in the text t = "ABABCABC". Positions count from 0. Here n = 8 is the text length and m = 3 the pattern length. A shift s means: put p under t starting at t[s].
t = "ABABCABC" n = 8 p = "ABC" m = 3 index 0 1 2 3 4 5 6 7 t A B A B C A B C shifts to try: s = 0 .. n - m = 0 .. 5
Read the lesson step by step
Find a pattern in text
Find every place the pattern p = "ABC" occurs in the text t = "ABABCABC". Positions count from 0. Here n = 8 is the text length and m = 3 the pattern length. A shift s means: put p under t starting at t[s].
t = "ABABCABC" n = 8 p = "ABC" m = 3 index 0 1 2 3 4 5 6 7 t A B A B C A B C shifts to try: s = 0 .. n - m = 0 .. 5Shift 0: compare left to right
Start at s = 0. Compare one character pair at a time: A = A, B = B, then A against C. They differ, so stop. Shift 0 is not a match, and it cost 3 comparisons. Each comparison drops a block on the tally.
s = 0 j = 0 t[0] A vs p[0] A equal j = 1 t[1] B vs p[1] B equal j = 2 t[2] A vs p[2] C differ: stop 3 comparisons, no matchSlide one place right
Slide the pattern one place: s = 1. The first pair is B against A. They differ at once, so this shift costs just 1 comparison. The two matches we saw at shift 0 are simply forgotten.
s = 1 j = 0 t[1] B vs p[0] A differ: stop 1 comparison, no match running total: 4Shift 2: a full match
At s = 2 all three pairs agree: A = A, B = B, C = C. The while loop runs off the end with j = 3 = m, so 2 goes into hits. A full match always costs m = 3 comparisons.
s = 2 j = 0 t[2] A vs p[0] A equal j = 1 t[3] B vs p[1] B equal j = 2 t[4] C vs p[2] C equal j == m: hits = [2] running total: 7Quick misses at 3 and 4
At s = 3 the first pair is B against A; at s = 4 it is C against A. Both fail on the first comparison, so each shift costs only 1. Most shifts in ordinary text end this fast.
s = 3 j = 0 t[3] B vs p[0] A differ s = 4 j = 0 t[4] C vs p[0] A differ running total: 9The last shift: n − m
s = 5 is the last shift, because the pattern must fit: n − m = 8 − 3 = 5. That is why the loop uses range(n − m + 1). All three agree, so hits = [2, 5]. Done.
s = 5 = n - m (the last shift that fits) t[5] A = A, t[6] B = B, t[7] C = C hits = [2, 5] range(n - m + 1) = range(6) = 0 .. 5Count the comparisons
The tally holds 3 + 1 + 3 + 1 + 1 + 3 = 12 comparisons. 6 shifts, each costing 1 to m = 3, so never more than (n − m + 1)·m = 18.
comparisons per shift s 0 1 2 3 4 5 cost 3 1 3 1 1 3 total 12 best case : n - m + 1 = 6 worst case : (n - m + 1)·m = 18The worst case
Now t = "AAAAAAAA" and p = "AAB". At every shift the two A's agree and only the last pair fails. Every shift costs the full m = 3, and the tally fills up: 6 × 3 = 18 comparisons, no matches.
t = "AAAAAAAA" p = "AAB" every shift: A = A, A = A, A vs B differ per shift 3 3 3 3 3 3 total 18 = (n - m + 1)·m hits = []How bad can it get?
So the worst case is Θ((n − m + 1)·m), which is O(nm). For a 1,000,000-character text and a 1,000-character pattern that is about a billion comparisons. The waste: it never reuses what a failed shift already learned.
worst case (n - m + 1)·m = Θ((n - m + 1)·m) = O(nm) n = 1,000,000, m = 1,000 (n - m + 1)·m = 999,001,000 best case n - m + 1 (first pair fails every time) extra space O(1) besides the hits list
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01The text has n = 10 characters and the pattern m = 4. How many shifts does naive search try?
The pattern must fit inside the text, so s runs from 0 to n − m = 6. That is n − m + 1 = 7 shifts, which is why the loop is range(n − m + 1).
02Searching for "ABC" in "ABABCABC", how many character comparisons does shift 0 make?
A = A and B = B agree, then A against C differs and the search stops. That is 3 comparisons.
03Which text and pattern make naive search do the most work for n = 8 and m = 3?
With all A's, every shift matches the first two characters and fails only on the last, so each of the 6 shifts costs 3: 18 = (n − m + 1)·m. With "XYZ" every shift fails at once: only 6 comparisons.
04What is the worst-case number of character comparisons of naive string search?
There are n − m + 1 shifts and each costs at most m comparisons, and inputs such as "AAAAAAAA" with "AAB" reach that bound. It is O(nm).
05In real Python code, how should you get the index of the first match of p in t?
str.find returns the lowest index where the substring is found, or -1. p in t only answers yes or no.
Glossary
- Text (t)
- The string you search in. Its length is n.
- Pattern (p)
- The string you search for. Its length is m, and m ≤ n.
- Shift (s)
- Where the pattern is placed: p[0] lines up under t[s]. Valid shifts run from 0 to n − m.
- Match
- A shift where every character agrees: t[s + j] == p[j] for all j from 0 to m − 1.
- Character comparison
- One test of t[s + j] == p[j]. The lesson counts these as the cost.
- Worst case
- The input of a given size that makes the algorithm do the most work, here (n − m + 1)·m comparisons.
- Naive (brute-force) algorithm
- One that tries every possibility in turn without reusing what earlier tries learned.
Notes and sources
- We count character comparisons t[s+j] == p[j], the cost model used by Sedgewick and Wayne. When j reaches m the test j < m fails first, so a full match costs exactly m comparisons.
- CLRS §32.1 gives the naive matcher a worst case of O((n − m + 1)·m), reached for example by a text of all a’s and a pattern of all a’s; that bound is tight. When m is about n/2 it is quadratic in n.
- On random text the expected count is much smaller: Sedgewick and Wayne show at most 2(n − m + 1) comparisons on average for random strings over an alphabet of two or more letters. Repetitive text and patterns are the bad case.
- In real Python code use t.find(p), which returns the lowest index of a match or -1, or p in t to test only membership. The function here returns every match: search("ABABCABC", "ABC") gives [2, 5].
- The partial match at shift 0 (A, B) is thrown away when the pattern slides. The next lesson, KMP: never look back, keeps that knowledge so the text is never re-read.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §32.1 The naive string-matching algorithm
- Sedgewick and Wayne, Algorithms 4th ed., §5.3 Substring Search
- Sedgewick and Wayne, lecture slides 5.3 Substring Search (brute force: worst case ~ M N char compares)
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 9 notes: string matching, simple algorithm
- Python documentation: str.find and the in operator
Quiz Unlocks after the last step.