Build the prefix table
For pattern ABABC, the table is [0, 0, 1, 2, 0]. The prefix ABAB ends in AB, which is also a prefix, so its entry is 2. This table is sometimes called the LPS or failure table.
Reuse a partial match
Suppose the search has matched ABAB but the next text character does not match C. The table says the final AB could still match the start of the pattern. KMP keeps that overlap and resumes at pattern index 2 instead of restarting from zero. The text index never moves backward.
Choose KMP search and follow a mismatch; then compare with Naive search (compare). The naive method restarts after each mismatch and can revisit many text positions. KMP builds the table in O(m) time and scans the text in O(n), for total O(n + m) time and O(m) extra space, where n is text length and m is pattern length.
Why the bound is linear
Each text character advances the text index once. The pattern index can fall back through table entries, but across the scan it cannot increase more times than the text index advances. The preprocessing and scan are therefore linear in their input lengths. KMP can process a stream because it does not need to rewind the text.
When to use it
KMP is useful when a worst-case linear bound matters or when text arrives as a stream. Boyer–Moore often skips more characters on natural-language text and can be faster in practice, but its performance depends on the pattern, alphabet, and implementation. Choose based on the data and required guarantees.
Common mistakes with KMP String Matching
- Using the longest prefix instead of a proper prefix: an entry cannot equal the whole pattern prefix.
- Resetting the pattern index to zero after every mismatch: that discards the overlap KMP was designed to keep.
- Moving the text index backward: KMP’s linear scan depends on keeping it monotonic.
- Confusing substring search with many-pattern search: KMP handles one pattern; Aho–Corasick is designed for many patterns.