← capítulo

Naive matching and KMP

Find a pattern in a text without ever backing up the text pointer. Speed from a precomputed failure table.

A mismatch is information

The failure function

Watch the pattern slide

Blue = comparing · green = matched · red = mismatch. After abab fails, the pattern jumps forward — no rewind.

Linear vs quadratic

aaaa…a vs aaaa…b: naive 398K comparisons, KMP 16K → 25× fewer.

Takeaway

Naive isn't wrong — it's fragile (latent quadratic on repetitive input). KMP pays O(m) setup for a linear guarantee, whatever the input. Next: Rabin-Karp — compare numbers (rolling hash), not strings.