Suppose you want to find every occurrence of the word "ABAB" inside a long document. The obvious way: line up the pattern at position 0, compare character by character until either a mismatch or a full match, then slide the pattern one position forward and repeat.
This naive approach is simple, but it wastes work. When you shift one position, you throw away everything you just learned about the characters you already read. In the worst case — think of searching "AAAA…AAAB" for "AAAB" — every shift re-reads almost the entire pattern against nearly the same text, blowing up to comparisons.
In 1977, Donald Knuth, Vaughan Pratt and James Morris published an algorithm that makes the cost exactly — linear in the total length of text and pattern combined. The key insight: after a mismatch, the pattern itself tells you how far you can safely jump without missing any match. That self-knowledge lives in a precomputed failure function (also called the partial-match table), and once you have it, the search never moves the text pointer backwards.
KMP belongs to the solved class — it is a deterministic polynomial-time algorithm (in fact linear time) with a complete correctness proof. No open questions remain about its fundamental complexity.
Comments
Loading comments...