1. Gyanastra
  2. Algorithms
  3. String Matching: Naive Search and Rabin-Karp
  4. The Problem, Stated Precisely
Free lesson, no account needed 4 min read

Algorithms · String Matching: Naive Search and Rabin-Karp

The Problem, Stated Precisely

We are given:

  • a text TT of length nn (characters T[0],T[1],…,T[n−1]T[0], T[1], \dots, T[n-1]),
  • a pattern PP of length mm (characters P[0],…,P[m−1]P[0], \dots, P[m-1]),

with m≤nm \le n. We must report every shift ss, 0≤s≤n−m0 \le s \le n-m, such that

T[s+j]=P[j]for all j=0,1,…,m−1.T[s+j] = P[j] \quad \text{for all } j = 0, 1, \dots, m-1.

Such an ss is called a valid shift (or an occurrence); any other ss is an invalid shift. There are exactly n−m+1n-m+1 candidate shifts.

Convention note (0-based vs 1-based). Most program code and most exam questions use 0-based arrays, so shifts run 0≤s≤n−m0 \le s \le n-m. CLRS indexes T[1..n]T[1..n] and P[1..m]P[1..m] but still defines a shift ss as an offset with 0≤s≤n−m0 \le s \le n-m. Some texts instead label an alignment by the 1-based start position, 1≤s≤n−m+11 \le s \le n-m+1. The count of shifts is n−m+1n-m+1 in every convention; only the labels differ. If a question says "the shift is 3", check whether it means the offset or the position. When in doubt, answer with the count n−m+1n-m+1 or with the substring itself.

Notation table.

SymbolMeaning
nnlength of text TT
mmlength of pattern PP
ssshift (start index of an alignment)
ddalphabet size (radix), e.g. d=10d=10 for digits, d=26d=26 for lowercase letters
qqa prime modulus used in Rabin-Karp
h(s)h(s)hash of the length-mm window T[s…s+m−1]T[s \dots s+m-1]

2.1 The method

For each shift s=0,1,…,n−ms = 0, 1, \dots, n-m:

  1. Set j←0j \leftarrow 0.
  2. While j<mj < m and T[s+j]=P[j]T[s+j] = P[j], increment jj.
  3. If j=mj = m, report ss (a match). Otherwise move to the next ss.
NAIVE-MATCH(T, P)
  n = length(T); m = length(P)
  for s = 0 to n-m
      j = 0
      while j < m and T[s+j] == P[j]
          j = j + 1
      if j == m
          print "Pattern occurs at shift" s

2.2 Complexity

  • Worst case: O(nm)O(nm). Every one of the n−m+1n-m+1 shifts may compare up to mm characters. Precisely, the number of character comparisons is at most (n−m+1) m(n-m+1)\,m.
  • Best case: O(n)O(n) (more precisely Θ(n−m+1)\Theta(n-m+1)). This happens when the first character of the pattern never matches the text at any shift — e.g. T=aaa…aT = aaa\dots a, P=bP = b. Then each shift costs exactly 1 comparison.
  • Average case: for a random text over an alphabet of size dd, the expected number of comparisons per shift is about 1+1/d+1/d2+⋯<d/(d−1)1 + 1/d + 1/d^2 + \dots < d/(d-1), so the expected total is O(n)O(n) for a fixed alphabet. (This is why naive search is fine in practice on natural text.)
  • Space: O(1)O(1) extra.

2.3 The worst-case input (memorize this)

The classic worst case is

T=aa⋯a⏟n,P=aa⋯a⏟m−1b.T = \underbrace{aa\cdots a}_{n},\qquad P = \underbrace{aa\cdots a}_{m-1}b .

At every shift, the first m−1m-1 characters match and only the last fails, so each shift costs mm comparisons. Total =(n−m+1) m=O(nm)= (n-m+1)\,m = O(nm).

Worked count. Let n=10n = 10, m=4m = 4, T=aaaaaaaaaaT = aaaaaaaaaa, P=aaabP = aaab. Number of shifts =n−m+1=10−4+1=7= n-m+1 = 10-4+1 = 7. Comparisons per shift =4= 4 (three aa's match, the bb fails). Total comparisons =7×4=28= 7 \times 4 = 28. Check: 28=(n−m+1)m=7⋅428 = (n-m+1)m = 7\cdot 4. ✓

A second classic worst case: T=aaa…aT = aaa\dots a, P=am−1bP = a^{m-1}b as above; also T=000…0T = 000\dots0, P=00…01P = 00\dots01 over binary.

2.4 Worked example (small, fully traced)

T=abababcT = \texttt{abababc}, n=7n = 7; P=ababcP = \texttt{ababc}, m=5m = 5. Shifts s=0,1,2s = 0,1,2 (since n−m=2n-m = 2).

ssalignmentcomparisonsresult
0ababc vs ababaa=a, b=b, a=a, b=b, c≠a → 5 comparisonsfail
1ababc vs bababb≠a → 1 comparisonfail
2ababc vs ababca=a,b=b,a=a,b=b,c=c → 5 comparisonsmatch at s=2

Total comparisons =5+1+5=11= 5+1+5 = 11. The pattern occurs at shift 2 (0-based), i.e. position 3 in 1-based indexing.


Pages 1–2 of 2