KMP (Knuth-Morris-Pratt)
A string search that precomputes a failure function (LPS) so that, on a mismatch, it skips ahead instead of re-comparing the pattern from the start. It never rewinds the text pointer, matching in O(n+m).
01KMP (Knuth-Morris-Pratt)
Explore How It WorksKMP starts. The failure function LPS precomputes prefix info for 'ABABC', so on a mismatch the text never rewinds — only the pattern skips ahead.
Line the pattern up with the start of the text. The first four chars, ABAB, match right through.
The fifth char is where they part: the text has D, the pattern has C.
The AB ending the matched ABAB is also the pattern's own prefix. Pull the pattern forward by just that much — two cells — and it still misses.
There is no prefix left to reuse, so move the pattern five cells on. Never rewinding our place in the text is the heart of KMP.
At the new position all five chars, ABABC, match.
Search complete · the pattern starts at index 5. The text was never rewound, so it finishes in O(n+m).
02 Understand It Simply
For EveryonePrecomputes, for every prefix, where to resume after a mismatch. The text is therefore scanned once, never backtracked.
Precomputes the pattern's failure function (LPS) so that on a mismatch it advances the pattern without rewinding the text.
No wasted comparisons — O(n+m).
- –Text search
- –log and DNA-sequence matching
- –grep-like tools
03 Python Implementation
A clean, readable reference implementation of the core logic of KMP (Knuth-Morris-Pratt).
04 Frequently Asked Questions
FAQWhat is KMP (Knuth-Morris-Pratt)?+
A string search that precomputes a failure function (LPS) so that, on a mismatch, it skips ahead instead of re-comparing the pattern from the start. It never rewinds the text pointer, matching in O(n+m).
What is the time complexity of KMP (Knuth-Morris-Pratt)?+
The time complexity of KMP (Knuth-Morris-Pratt) is O(n + m). Follow the step-by-step visualization to see exactly why.
Where is KMP (Knuth-Morris-Pratt) used?+
Text search, log and DNA-sequence matching, grep-like tools.
What's a simple analogy for KMP (Knuth-Morris-Pratt)?+
Precomputes, for every prefix, where to resume after a mismatch. The text is therefore scanned once, never backtracked.
