Pattern matching answers a single question: where does a short string occur inside a longer one? Browsers run it for Ctrl+F. Genome tools run it across 3 billion base pairs of DNA. Intrusion-detection systems run it at line rate on every network packet that passes through. Naive scanning is O(n*m), and for the last two workloads that is too slow.
This chapter defines the problem, and lists the algorithms that solve it.
Given a text T of length n and a pattern P of length m (where m <= n), find all positions i in T where the substring T[i..i+m-1] equals P.
Terminology:
The pattern slides along the text. At each position, the characters are compared.
At position 3, every character of the pattern matches the corresponding character in the text. That is a match.
A few representative workloads:
The last three workloads are why the textbook algorithms matter. The first two work fine with naive search for typical inputs but benefit from better algorithms on large files.
Given a text T of length n and a pattern P of length m, return all starting indices where P occurs in T.
Some problems ask only for the first occurrence (return -1 if not found). Others ask for all occurrences, or just a count. Every algorithm covered here handles all three variants with minor changes.
? (any single character) or * (any sequence).Function signature for the basic problem:
The four algorithms covered in this course, plus two more worth knowing about:
| Algorithm | Time (Worst) | Time (Average) | Space | Preprocessing | Best For |
|---|---|---|---|---|---|
| Brute Force | O(n * m) | O(n) | O(1) | None | Short patterns, simple cases |
| KMP (Knuth-Morris-Pratt) | O(n + m) | O(n + m) | O(m) | Failure function | Guaranteed linear time |
| Rabin-Karp | O(n * m) | O(n + m) | O(1) | Hash computation | Multiple pattern search |
| Z-Algorithm | O(n + m) | O(n + m) | O(n + m) | Z-array | Prefix-based problems |
Brute force has no preprocessing. On short patterns or average-case inputs it does fine; on adversarial inputs it hits O(n*m).
KMP and Z-Algorithm guarantee O(n+m) in the worst case by preprocessing the pattern to avoid redundant comparisons. The O(m) preprocessing pays for itself on long texts.
Rabin-Karp's worst case matches brute force, but its expected case is O(n+m) and it can search for many patterns in a single pass over the text by hashing each pattern and looking up window hashes in a hash set.
Two algorithms not covered but worth knowing:
grep, glibc's memmem, and JDK's modern String.indexOf for long patterns.fgrep -f. The multi-pattern extension of KMP.This course focuses on Brute Force, KMP, Rabin-Karp, and Z-Algorithm because they are the algorithms most commonly tested in interviews and most commonly composed into other string problems.
The flowchart below maps common situations to the right algorithm:
fgrep -f.10 quizzes