Algorithms · String Matching: Naive Search and Rabin-Karp
The Problem, Stated Precisely
We are given:
- a text of length (characters ),
- a pattern of length (characters ),
with . We must report every shift , , such that
Such an is called a valid shift (or an occurrence); any other is an invalid shift. There are exactly candidate shifts.
Convention note (0-based vs 1-based). Most program code and most exam questions use 0-based arrays, so shifts run . CLRS indexes and but still defines a shift as an offset with . Some texts instead label an alignment by the 1-based start position, . The count of shifts is 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 or with the substring itself.
Notation table.
| Symbol | Meaning |
|---|---|
| length of text | |
| length of pattern | |
| shift (start index of an alignment) | |
| alphabet size (radix), e.g. for digits, for lowercase letters | |
| a prime modulus used in Rabin-Karp | |
| hash of the length- window |
2.1 The method
For each shift :
- Set .
- While and , increment .
- If , report (a match). Otherwise move to the next .
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: . Every one of the shifts may compare up to characters. Precisely, the number of character comparisons is at most .
- Best case: (more precisely ). This happens when the first character of the pattern never matches the text at any shift — e.g. , . Then each shift costs exactly 1 comparison.
- Average case: for a random text over an alphabet of size , the expected number of comparisons per shift is about , so the expected total is for a fixed alphabet. (This is why naive search is fine in practice on natural text.)
- Space: extra.
2.3 The worst-case input (memorize this)
The classic worst case is
At every shift, the first characters match and only the last fails, so each shift costs comparisons. Total .
Worked count. Let , , , . Number of shifts . Comparisons per shift (three 's match, the fails). Total comparisons . Check: . ✓
A second classic worst case: , as above; also , over binary.
2.4 Worked example (small, fully traced)
, ; , . Shifts (since ).
| alignment | comparisons | result | |
|---|---|---|---|
| 0 | ababc vs ababa | a=a, b=b, a=a, b=b, c≠a → 5 comparisons | fail |
| 1 | ababc vs babab | b≠a → 1 comparison | fail |
| 2 | ababc vs ababc | a=a,b=b,a=a,b=b,c=c → 5 comparisons | match at s=2 |
Total comparisons . The pattern occurs at shift 2 (0-based), i.e. position 3 in 1-based indexing.