Skip to content
StackDecode
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

  1. Preprocess the pattern into a "failure table": for each prefix, the length of the longest proper prefix that is also a suffix.
  2. Scan the text once. On a match, advance both positions.
  3. On a mismatch, do not move back in the text: use the table to slide the pattern to the next possible alignment.
  4. The text pointer never goes backwards, so the total work is O(n + m).

Watch it run

Loading animation…