Sub topic 1
The String Matching Problem
Searching for a word in a document, finding a gene sequence in a genome, and scanning network traffic for a known signature are all the same problem underneath. You have a long string, you have a short string, and you want to know where the short one appears inside the long one. This chapter defines that problem precisely, fixes the notation used for the rest of the tutorial, and sets out what a good solution must do. Later chapters cover the naive method, borders, the prefix function, and KMP itself.
Prerequisites
This chapter and the ones after it assume you are comfortable with:
- Basic programming in Python or a similar language
- Arrays, strings, and zero-based indexing, including slices such as
s[i:j] - Loops and conditionals
- Big-O notation for time and space complexity
All code uses Python 3. Slicing follows Python's rule: s[i:j] contains the characters at indices i through j - 1.
Stating the Problem Precisely
The exact string matching problem takes two inputs:
- A text
Tof lengthn - A pattern
Pof lengthm
Both are sequences of characters from some alphabet Σ. The alphabet is the set of symbols that can appear: ASCII bytes, Unicode code points, the four DNA bases A, C, G, T, or integers.
An occurrence of P in T is an index i with 0 <= i <= n - m such that
T[i:i + m] == PThe index i is also called a shift or offset, because you can picture sliding the pattern i positions to the right along the text and checking whether every character lines up. The task is to report every valid shift.
"Exact" means character-for-character equality. There are no wildcards, no allowed typos, and no case folding unless you normalize the strings yourself first. Approximate matching, where some edits are allowed, is a separate and harder family of problems.
Notation used throughout
| Symbol | Meaning | Column | Column |
|---|---|---|---|
| `T` | The text being searched | ||
| `P` | The pattern being searched for | ||
| `n` | `len(T)` | ||
| `m` | `len(P)` | ||
| `i` | A position in the text, usually the start of a candidate match | ||
| `T[i:i + m]` | The window of the text aligned with the pattern at shift `i` | ||
| Σ | The alphabet; σ = \ | Σ\ | is its size |
A worked example
Take T = "abababca" (so n = 8) and P = "abab" (so m = 4). The possible shifts are 0 through n - m = 4.
| Shift `i` | Window `T[i:i+4]` | Match? |
|---|---|---|
| 0 | `abab` | yes |
| 1 | `baba` | no |
| 2 | `abab` | yes |
| 3 | `babc` | no |
| 4 | `abca` | no |
The answer is [0, 2]. The two occurrences overlap: they share the characters T[2:4] = "ab". Correct matchers have to handle overlap, and it is the most common place where quick implementations go wrong.
Variants of the Output
Applications ask for different things, and the variant changes what a solution has to do.
| Variant | Output | Example use |
|---|---|---|
| Existence | `True` or `False` | "Does this log line contain `ERROR`?" |
| First occurrence | Smallest valid `i`, or `-1` | `str.find` |
| All occurrences | Every valid `i`, overlapping included | Highlighting search hits, genome motif counting |
| Non-overlapping occurrences | A greedy left-to-right subset | Search-and-replace |
| Count | How many occurrences | Statistics on motif frequency |
This tutorial targets all occurrences, overlapping included, because the other variants follow from it. Existence and first occurrence can stop at the first hit. Counting is the length of the list. Non-overlapping matches can be found by skipping ahead m positions after each reported hit.
A Reference Implementation for Testing
Before building anything clever, it helps to have a slow but trustworthy oracle to compare against. The function below uses str.find and restarts one position after each hit, so it finds overlapping occurrences. It is not the naive algorithm the next chapter analyzes. It is a specification you can run.
def all_occurrences(text, pattern):
"""Return every shift i where text[i:i+len(pattern)] == pattern,
including overlapping occurrences."""
if pattern == "":
# The empty pattern matches at every position, including the end.
return list(range(len(text) + 1))
result = []
i = text.find(pattern)
while i != -1:
result.append(i)
i = text.find(pattern, i + 1) # i + 1, not i + m, to allow overlap
return result
print(all_occurrences("abababca", "abab")) # [0, 2]
print(all_occurrences("aaaa", "aa")) # [0, 1, 2]
print("aaaa".count("aa")) # 2 (non-overlapping)
print(all_occurrences("abc", "abcd")) # [] (pattern longer than text)
print(all_occurrences("abc", "")) # [0, 1, 2, 3]The last two calls preview edge cases that get a full treatment later in the tutorial. When m > n there are no valid shifts, because the range 0 <= i <= n - m is empty. When m = 0, the empty string equals T[i:i] for every i from 0 to n, which gives n + 1 matches. That is the convention Python follows ("abc".find("") is 0), and the KMP code in later chapters follows it too.
What a Good Solution Must Do
A lower bound
Any correct algorithm has to look at enough of the text to rule out matches it does not report. In the worst case that means reading essentially every character, so no general algorithm beats Ω(n) for the search. It also has to read the pattern, which costs Ω(m). A matcher that runs in O(n + m) time is therefore optimal up to constant factors. KMP reaches that bound in the worst case.
The output can be large, which is a subtle point. For T = "a" * n and P = "a" * m, there are n - m + 1 occurrences. Writing them down takes time proportional to their number, but that number never exceeds n + 1, so it fits inside O(n + m).
Worst case, not just typical case
Many simple approaches are fast on ordinary English text and slow on adversarial input. Texts with long runs of repeated characters, such as "aaaa...ab", or periodic structure, such as "abababab...", are common in DNA, binary data, and machine-generated logs. An attacker who controls the input can also choose a bad case on purpose. This tutorial cares about guarantees that hold for every input.
Never moving backward in the text
KMP has a property beyond its running time: it reads the text strictly left to right, one character at a time, and never re-reads a character it has already passed. That makes it a streaming or online algorithm. You can feed it characters from a network socket, a pipe, or a file too large for memory, and it reports each match as soon as the last character of that match arrives. It needs only O(m) extra memory for the pattern and its precomputed table, and no buffer of past text.
Many faster-in-practice algorithms lack this property. Some jump backward to re-check characters, and some need random access into the text. When the text arrives as a stream, that difference matters more than constant-factor speed.
Preprocessing the pattern
In most applications the pattern is fixed and the text is long, or one pattern is searched for across many texts. That makes it worthwhile to spend O(m) time studying the pattern once, building a table that describes how the pattern overlaps with itself, and then using that table during every search. KMP's table is the prefix function, and most of the tutorial is about what it means, how to compute it, and why it lets the search skip work safely.
Common Mistakes When Framing the Problem
- Stopping the shift range at
n - m - 1. The last valid shift isn - m. In Python that isrange(n - m + 1). - Advancing by
mafter a match. This silently drops overlapping occurrences. Advance by one shift, or, in KMP, by an amount the prefix function guarantees is safe. - Comparing against a non-overlapping built-in.
str.count,re.findall, andre.finditerdo not report overlaps. - Forgetting the degenerate inputs. An empty pattern and a pattern longer than the text both need defined, tested behavior.
- Mixing up characters and bytes. If the text is UTF-8 bytes and the pattern is a decoded string, shifts refer to different units. Match bytes against bytes or code points against code points.
Where This Tutorial Goes Next
The next chapter implements the obvious solution, which compares the pattern at every shift, and shows an input where it costs O(n·m). The chapters after that introduce borders and the prefix function, compute the prefix function in linear time, and use it to build KMP search. The tutorial then proves KMP correct and linear, and covers its applications and its relationship to other matching algorithms.
Exercise
For T = "aabaabaab" and P = "aabaab", list every occurrence (overlapping included). What would a matcher that jumps ahead by m after each hit report instead?
Show answer
n = 9 and m = 6, so the shifts to check are 0 through 3. T[0:6] = "aabaab" matches, and T[3:9] = "aabaab" matches. T[1:7] = "abaaba" and T[2:8] = "baabaa" do not. The full answer is [0, 3]. A matcher that jumps by m = 6 after the hit at 0 resumes at shift 6, which is past the last valid shift of 3, so it reports only [0].
Exercise
For a text of length n and a pattern of length m, how many occurrences can there be at most, and which inputs reach that maximum? Explain why this does not stop an O(n + m) algorithm from existing.
Show answer
If 1 <= m <= n, there can be at most n - m + 1 occurrences, one per valid shift. A single repeated character reaches this, for example T = "a" n and P = "a" m. If m = 0 there are n + 1 occurrences. In every case the count is at most n + 1, so writing out the answer costs O(n) and fits inside O(n + m).
Exercise
Write a test that compares a matcher my_search(text, pattern) against all_occurrences on 10,000 random cases over the alphabet "ab", with text lengths 0 to 12 and pattern lengths 0 to 4.
Show answer
One correct version: import random def testmatcher(mysearch, trials=10000): for in range(trials): t = "".join(random.choice("ab") for in range(random.randint(0, 12))) p = "".join(random.choice("ab") for in range(random.randint(0, 4))) assert mysearch(t, p) == all_occurrences(t, p), (t, p) The small alphabet produces many repeats and overlaps. The length ranges cover the empty pattern, the empty text, and patterns longer than the text.