Why it matters

KMP is foundation of string matching. Understanding shapes text search.

Advertisement

The architecture

Failure function: longest proper prefix that is also suffix.

On mismatch: shift by failure.

KMP algorithmPreprocess patternfailure functionMatch textno backtrackShift on mismatchby failure valueFailure function computed in O(m); matching in O(n) — total O(n+m)
KMP.
Advertisement

How it works end to end

Failure[i] = longest proper prefix-suffix of pattern[0..i].

On mismatch at pattern[j], skip to failure[j-1].

Text position never decreases.