Knuth-Morris-Pratt — Matching Without Re-Reading

On a mismatch, KMP slides the pattern by the failure link lps[j-1] instead of restarting. The text pointer never moves backward, giving O(n + m).

step 0

Text & pattern alignment

Text T (index i scans forward, never backward)
Pattern P (slides right via the failure link on mismatch)
i = 0 j (matched length) = 0 pattern offset = 0 comparisons = 0
matches: (none yet)

Prefix function (lps array of the pattern)

matched comparing mismatch lps value used
Press Step to begin. We compare T[i] with P[j]; on a mismatch we set j = lps[j-1] and keep i fixed.

How to read this animation

The lps panel below the tapes shows the prefix function of the pattern: lps[i] is the length of the longest proper prefix of P[0..i] that is also a suffix. On a mismatch at pattern index j, KMP reads lps[j-1] (highlighted gold) and that becomes the new j — the pattern visually slides right by j - lps[j-1] positions, never restarting at the beginning. This is precisely why the algorithm is linear: no text character is ever compared as a fresh start twice.

Self-contained visualization. The pattern offset shown is i - j; on a mismatch the offset jumps forward by the failure link instead of by 1. See junior.md for the walkthrough and professional.md for the proof that the text index never moves backward. The comparison counter at the top stays linear in the input size — drive k with a long repetitive text to see it never blow up quadratically.