AlgoPlus//strings / kmp
Read the theory

Knuth-Morris-Pratt (KMP)

A prefix table lets the pattern jump forward without ever re-matching text.

Shift
Comparisons
Matches
Text
Pattern
Legend
Comparing
Match
Mismatch
AI Tutor Workspace
In a nutshell
KMP (Knuth-Morris-Pratt) never re-reads text it has already matched. Before searching, it builds a small prefix table from the pattern — also called the failure function — recording, for each position, the longest stretch of the pattern's own start that also appears ending right there. When a mismatch happens partway through, that table says exactly how far the pattern can jump forward without losing the part already matched, so the text is scanned just once, in linear time.
Ready
Press play to begin the cinematic walkthrough.
When a mismatch happens you already know the matched prefix — the lps table tells you how far you can safely jump without re-reading text.
Key terms
Go deeper in the lesson
Read the full theory, intuition & complexity for Knuth-Morris-Pratt (KMP).