StringsAnimated
KMP Algorithm
Use a failure table so the text pointer never moves backwards.
Time
O(n + m)
Extra space
O(m)
Use it for
Repeated patterns, streaming input.
How it works
- Preprocess the pattern into a "failure table": for each prefix, the length of the longest proper prefix that is also a suffix.
- Scan the text once. On a match, advance both positions.
- On a mismatch, do not move back in the text: use the table to slide the pattern to the next possible alignment.
- The text pointer never goes backwards, so the total work is O(n + m).
Watch it run
Loading animation…