The Knuth-Morris-Pratt Algorithm

The Knuth-Morris-Pratt algorithm builds a failure function for the pattern. Consider again the pattern p=AAATA:

Consider again searching in the text t=AATAAAATA:

  1. AATAAAATA

  2. AATAAAATA

  3. AATAAAATA

  4. AATAAAATA

  5. AATAAAATA

  6. AATAAAATA

  7. AATAAAATA

  8. AATAAAATA

  9. AATAAAATA

  10. AATAAAATA

The Knuth-Morris-Pratt algorithm always requires around n+m operations in the worst case where m is the length of p and n is the length of t.