The problem
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].
Sliding the pattern
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.
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.
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.
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 = 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.
What it costs
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.
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.
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.
What happens
;; step 1/9 · problem 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
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.