Sub topic 1
The String Matching Problem
Prerequisites
This chapter assumes you can read basic Python and are comfortable with arrays, strings, and zero-based indexing. You should know loops and conditionals, and you should be able to read Big-O notation for time complexity.
The String Matching Problem
You are given a text T of length n and a pattern P of length m. Exact string matching means finding every index i where T[i:i+m] == P. Occurrences may overlap. In "abababca", the pattern "abab" occurs at indices 0 and 2.
Naive Search and Why It Can Be Slow
The simplest approach tries every shift and compares the pattern there:
def naive_search(text, pattern):
n, m = len(text), len(pattern)
return [i for i in range(n - m + 1) if text[i:i + m] == pattern]
print(naive_search("abababca", "abab")) # [0, 2]The worst case costs O(n · m). Take text "aaaa...a" and pattern "aa...ab". At every shift, the first m - 1 characters match and only the last one fails. Naive search then moves one position forward and compares all of those characters again, even though it already knows what they are. KMP avoids this repeated work.
Prefixes, Suffixes, and Borders
A proper prefix of s is a prefix that is shorter than s. A proper suffix is defined the same way. A border is a string that is both a proper prefix and a proper suffix of s.
| String | Borders | Longest border |
|---|---|---|
| `abab` | `ab` | `ab` (length 2) |
| `abacaba` | `a`, `aba` | `aba` (length 3) |
| `abc` | none | empty (length 0) |
Borders matter for matching. Suppose P[0..k-1] has matched and the next character fails. The next shift that could still produce a match lines up the longest border of the matched part.
The Prefix Function
The prefix function pi[i] is the length of the longest border of P[0..i]. Other names for it are the failure function and the LPS ("longest proper prefix that is also a suffix") array.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
print(prefix_function("abacaba")) # [0, 0, 1, 0, 1, 2, 3]When the comparison at p[k] fails, the code falls back to the next shorter border through pi[k - 1]. A later chapter explains why this runs in linear time.
Exercise
Compute the prefix function of "aabaaab" by hand.
Show answer
[0, 1, 0, 1, 2, 2, 3]. At index 5 ("aabaaa"), the border "aaa" fails, so the code falls back to "aa". At index 6, extending that border gives "aab", so pi[6] = 3.