Linear matching by reusing a pattern's prefix structure
Do not throw away a successful prefix
A naive matcher restarts the pattern after every mismatch, repeatedly scanning the same text. KMP preprocesses the pattern into an LPS table. lps[k] is the length of the longest proper prefix of P[0..k] that is also a suffix.
Jump the pattern, not the text
Pointer i scans the text and j scans the pattern. Equal characters move both pointers. On a mismatch with j > 0, set j = lps[j-1] and keep i fixed. The pattern slides to the longest prefix that can still match what has already been seen.
T
a
b
a
b
a
b
c
a
b
P
a
b
a
b
c
π
0
0
1
2
0
Align the pattern with the start of the text; both pointers begin at 0.
19if (j === m) { res.push(i - m); j = lps[j -1]; } // match found
20 } elseif (j >0) {
21 j = lps[j -1]; // mismatch: jump without rewinding i
22 } else {
23 i++; // mismatch at j=0: advance the text
24 }
25 }
26return res;
27}
Text Tabababcab
Pattern Pababc
i (text)0
j (pattern)0
MatchesNone
1 / 12
Why it is linear
The text pointer never moves backward, and LPS jumps strictly reduce the pattern pointer when they do not advance the text. Pattern preprocessing costs O(m) and matching costs O(n), for O(n + m) total time and O(m) extra space.
KMP is useful anywhere exact substring search must be predictable: editors, command-line text tools, protocol parsers, and biological sequence matching. Its central lesson is broader: preprocess structure once so mismatches can skip work later.