Implement substring search (strStr)
The naive scan re-reads text after every mismatch, which is O(n·m) and genuinely quadratic on repetitive input. KMP precomputes how far the pattern can safely slide, so the text index never moves backwards and the whole search is O(n + m).
Overview
What naive search wastes
Align the pattern at position 0, compare until a mismatch, then restart at position 1. The waste is that the comparisons already made are thrown away: on "aaaaaab" against "aaab", almost every alignment re-reads the same characters.
Worst case O(n·m). Average case on natural text is close to O(n), which is why naive search is a perfectly reasonable answer to give first — then improve it.
Step through it
What to watch
- The table is built first, from the pattern alone.
- On a mismatch the pattern slides;
istays put. - That single property is the whole complexity difference.
Say this out loud
"Naive is O(n·m) and fine for most inputs. KMP builds a prefix table so on a mismatch the pattern slides instead of the text rewinding - O(n + m), and the text pointer only ever moves forward."