Home
DSA Course
Strings
KMP Algorithm
KMP Algorithm
Visualize the Knuth-Morris-Pratt algorithm for efficient pattern searching using the LPS array.
KMP Algorithm
1. LPS Array Construction
-
0A
-
1B
-
2A
-
3B
-
4C
-
5A
-
6B
-
7A
-
8B
2. Pattern Search
A
0B
1A
2B
3D
4A
5B
6A
7C
8D
9A
10B
11A
12B
13C
14A
15B
16A
17B
18Controls
Ready
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.Intuition
The Naive approach backtracks the text pointer unnecessarily. KMP uses the pattern's own structure (LPS array) to skip characters that we know will match, avoiding redundant comparisons.
Concept
- LPS Array: Stores the length of the longest proper prefix which is also a suffix for each sub-pattern.
- Optimization: When a mismatch occurs at pattern index
j, we don't resetjto 0. We reset it toLPS[j-1]. - Complexity: O(N + M) time, where N is text length and M is pattern length.
How it Works
Algorithm:
- Build LPS: Compute LPS array for the pattern.
- Search: Iterate through text with index
iand pattern with indexj. - If match, increment both.
- If mismatch, update
j = LPS[j-1](don't movei). - If
j == M, pattern found! Resetj = LPS[j-1].
Step-by-Step Breakdown
Watch the visualization:
- Phase 1: See how the LPS array is built by comparing prefixes and suffixes.
- Phase 2: See the pattern slide. Notice how it jumps forward on mismatches instead of sliding by just 1.
When to Use
- Searching in large texts.
- Streaming text search.
When NOT to Use
- Very short patterns (overhead of LPS might not be worth it).
How to Identify
"Pattern matching", "Avoid backtracking", "O(N) search".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
