What is the KMP Algorithm?
The Knuth-Morris-Pratt algorithm speeds up string matching by never re-examining a text character it has already matched. It precomputes an LPS ("longest proper prefix that is also a suffix") array from the pattern alone, which tells it exactly how far to shift the pattern after a mismatch instead of restarting from the beginning.
This guarantees linear O(n + m) time in the worst case, unlike the naive approach's O(n · m), and unlike Rabin-Karp, KMP never has to deal with hash collisions since it works directly on characters.
Time & Space Complexity
- Build LPS ArrayO(m)
- Search PhaseO(n)
- SpaceO(m)
* n = text length, m = pattern length. No worst-case blowup, unlike naive search.
Real-World Use Cases
- ✓Text EditorsPowering reliable "find" functionality with guaranteed linear-time search.
- ✓Network Intrusion DetectionScanning packet streams for known attack signatures in real time.
- ✓BioinformaticsFinding exact substring matches within DNA or protein sequences.