String Matching
Algorithms · Advanced Placement
String Matching: the big picture
String matching asks where a pattern occurs in a text, and the naive algorithm compares the pattern against every alignment, costing the product of the two lengths in the worst case. Better algorithms avoid re-examining text characters already known to match. The Knuth–Morris–Pratt algorithm precomputes, for each pattern prefix, the length of the longest proper prefix that is also a suffix, which tells it how far the pattern can be shifted on a mismatch without missing an occurrence; the preprocessing is linear in the pattern length and the search is linear in the text length, with no character examined more than twice. The Rabin–Karp algorithm hashes the pattern and each text window, comparing hashes rather than characters and using a rolling hash so each window costs constant time; it is probabilistic in that hash collisions require verification, and it extends naturally to two-dimensional and multiple-pattern matching. The Boyer–Moore algorithm scans the pattern right to left and uses mismatch information to skip ahead, often examining far fewer than all text characters, which makes it the fastest in practice for long patterns and large alphabets. Suffix trees and suffix arrays preprocess the text instead, answering many queries efficiently.
Naive Matching, Knuth–Morris–Pratt & Rabin–Karp
The naive matcher restarts from scratch after every mismatch, throwing away everything it just learned. Knuth–Morris–Pratt keeps that information: it precomputes, for each pattern prefix, the longest proper prefix that is also a suffix, which says exactly how far to shift without missing anything. No text character is examined more than twice. Rabin–Karp takes a different route, comparing rolling hashes rather than characters, which makes each window constant-time and extends naturally to searching for many patterns at once.
{{illustration:algos-l18-f1}}
{{illustration:algos-l18-f2}}
Key relations
- Matching bounds and the rolling hash. T_KMP = O(n + m) ; hᵢ₊₁ = ((hᵢ − tᵢd^(m−1))d + tᵢ₊ₘ) bmod q
Suffix Arrays, Boyer–Moore & Text Indexing
When one text is searched many times, it pays to preprocess the text instead of the pattern. A suffix array lists every suffix's starting position in sorted order, which turns pattern search into a binary search. Boyer–Moore takes the opposite approach for single searches: scan the pattern right to left and use the mismatched character to skip ahead, often examining a fraction of the text. That sublinear behaviour in practice is why it or a variant is behind most grep implementations.
{{illustration:algos-l18-f3}}
{{illustration:algos-l18-f4}}
Key relations
- Indexing and skipping bounds. T_build = O(nlog n) ; T_query = O(mlog n) ; T_BM = Ω(n/m) typical