Find pattern in text efficiently using the prefix table (failure function)
Naive search is O(nm) because it restarts from position 1 after each mismatch. KMP observes that a mismatch at pattern[j] means text[i-j..i-1] matches pattern[0..j-1]. The failure function encodes: "if mismatch at j, what's the longest proper prefix of pattern[0..j-1] that's also a suffix?" This allows jumping directly to the next possible match position.
The text index i never decreases—guaranteeing linear time. The amortized cost of pattern index retreats is bounded by advances.
The failure function π[j] stores the length of the longest proper prefix of pattern[0..j] that is also a suffix. This is a function solely of the pattern, independent of the text. Once computed, it can be reused for multiple texts without rebuilding.
KMP is an online algorithm: it processes the text character-by-character and can match patterns in streaming data with constant additional space per character.