0A1B2A3B4C5A6B7Cs=0s=1s=2s=3s=4s=51def search(t, p):2 n, m = len(t), len(p)3 hits = []4 for s in range(n - m + 1):5 j = 06 while j < m and t[s+j] == p[j]:7 j += 18 if j == m:9 hits.append(s)10 return hitss0jcompares0hits[]p[0]Ap[1]Bp[2]C==≠≠
Mint cells: the pattern, sliding one place per shiftCaps: the pair being compared, lime = equal, red = differTally blocks: comparisons made at each shiftThe pattern ABC slides along the text ABABCABC one place per shift; each character comparison drops one block on the tally slot for that shift. Matches at 2 and 5 cost 12 comparisons. On AAAAAAAA with AAB every slot fills: (n − m + 1)·m = 18.

The problem

  1. 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

What it costs

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.