Knuth–Morris–Pratt String Search
On a mismatch, use the prefix information to keep the part of the match that is still valid.
Core Intuition & How It Works
The Knuth–Morris–Pratt (KMP) algorithm achieves guaranteed O(n + m) string search by precomputing a longest proper prefix-suffix (LPS) table. On a mismatch, KMP shifts the pattern without ever moving the text pointer backward.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n + m) |
| Space Complexity | O(m) |
| Topic Chapter | Chapter 3: Array & String Techniques |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Use the LPS failure function to reuse already-matched prefix characters instead of restarting from pattern index 0.
Common Pitfalls & Edge Cases
Confusing the LPS fallback loop (falling back via lps[len - 1] until match or 0) with a single if-statement.
Real-World & Technical Interview Applications
Text editors, bioinformatics motif search, intrusion detection signatures, and streaming pattern matchers.