Lesson 16 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(n + m)
Space ComplexityO(m)
Topic ChapterChapter 3: Array & String Techniques
Difficulty LevelIntermediate

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.