Sub topic 1
The String Matching Problem
Searching for a word in a document, finding a gene sequence in a genome, and scanning log files for an error code all come down to one task: given a long string, find every place where a shorter string appears. This chapter defines that task precisely and sets the vocabulary used for the rest of the tutorial.
Prerequisites
This chapter assumes you are comfortable with the following:
- Basic programming in Python or a similar language
- Arrays, strings, and zero-based indexing
- Loops and conditionals
- Big-O notation for time and space complexity
Defining the Problem
The exact string matching problem takes two inputs:
- A text
Tof lengthn. - A pattern
Pof lengthm, usually much shorter than the text.
The goal is to report every shift i (also called an occurrence or match position) such that T[i:i+m] == P. In other words, the pattern lines up character for character with the text starting at index i. Valid shifts range from 0 to n - m.
"Exact" means no wildcards, no case folding, and no tolerance for typos. Approximate matching is a separate family of problems.
| Term | Symbol | Example |
|---|---|---|
| Text | `T`, length `n` | `"abababca"`, `n = 8` |
| Pattern | `P`, length `m` | `"abab"`, `m = 4` |
| Shift | `i` | `0` and `2` |
All Occurrences, Including Overlaps
Many library functions, such as Python's str.find, return only the first match. This tutorial asks for all matches, and matches may overlap. In "abababca", the pattern "abab" starts at index 0 and again at index 2. The two occurrences share the characters "ab" at indices 2 and 3.
Overlaps cause a common mistake. After finding a match at shift i, it is tempting to resume searching at i + m. That skips the match at shift 2 in the example above. Python's str.count makes this mistake on purpose, because it counts only non-overlapping occurrences.
The following reference function defines the expected output. It uses str.find and restarts one position after each hit, so overlapping matches are reported:
def all_occurrences(text, pattern):
result = []
i = text.find(pattern)
while i != -1:
result.append(i)
i = text.find(pattern, i + 1)
return result
print(all_occurrences("abababca", "abab")) # [0, 2]
print("abababca".count("abab")) # 1 (non-overlapping only)
print(all_occurrences("aaaa", "aa")) # [0, 1, 2]
print(all_occurrences("abc", "abcd")) # []You can use this function as a test oracle when you build your own matcher later. It does not tell you anything about efficiency.
Measuring Cost
Algorithms for this problem are compared by how many character comparisons they make as a function of n and m. Two costs matter:
- Preprocessing work done on the pattern alone, before the text is read.
- Matching work done while scanning the text.
The output itself can be large. In "aaaa...a" with pattern "a", there are n matches, so any algorithm needs at least O(n) time just to report them. A lower bound of O(n + m) also applies, because every character of the text and the pattern may need to be read.
The next chapter shows that the obvious approach can need O(n · m) comparisons. The Knuth-Morris-Pratt algorithm reaches the O(n + m) bound, and it reads the text strictly left to right without ever moving backward. That property matters for streamed input, where earlier characters may no longer be available.
Exercise
List every shift at which the pattern "ana" occurs in the text "bananarama". Then state what a search that resumes at i + m after each match would return instead.
Show answer
The shifts are [1, 3]: "ana" starts at index 1 ("b|ana|narama") and at index 3 ("ban|ana|rama"), and the two matches overlap at index 3. A search that resumes at i + m jumps from 1 to 4 and returns only [1].
Exercise
For a text of length n = 10 and a pattern of length m = 3, what is the range of valid shifts, and what does the empty pattern return on that text?
Show answer
Valid shifts run from 0 to n - m = 7, which is 8 candidate positions. The empty pattern matches at every index from 0 to 10, giving 11 matches.