SnapDevCode

KMP String Search

LeetCode
Comparisons0
Pattern Shifts0
Matches Found0
Step 1 / 0
Ready to run KMP Algorithm.
LPS Table (Longest Prefix Suffix)Pattern Length = 7
[0]
A
0
[1]
B
0
[2]
A
0
[3]
C
0
[4]
A
0
[5]
B
0
[6]
A
0
Pointer Alignment Grid
Match Mismatch
TEXT
A
▲ i
B
A
B
A
C
A
B
A
C
A
B
A
PAT
A
▲ j
B
A
C
A
B
A
>_ Code Execution

🧠 First Principles: What is KMP actually doing?

At its core, KMP (Knuth-Morris-Pratt) is about Memory and Salvaging Work.

When a regular brute-force search hits a "mismatch" (a mistake), it throws away everything it just saw, moves one step forward, and blindly starts over from scratch. KMP asks a fundamental question: "Based on the history of what we literally just looked at, how much of our work can we save?"

⚡ The Secret to its Speed: Because KMP remembers what it just matched, your reading pointer in the main text NEVER moves backward! It sweeps left-to-right exactly once, making it drastically faster than regular searching.

🎮 The Real-World Analogy: The Cheat Code

Imagine you are entering a secret 6-button cheat code in a gaming console to unlock a door:

⬆️UP
⬆️UP
⬇️DOWN
⬆️UP
⬆️UP
➡️RIGHT

You are doing great! You press the first 5 buttons correctly: ⬆️ ⬆️ ⬇️ ⬆️ ⬆️.
But on the 6th button, your thumb slips and you press ⬇️ (DOWN) instead of ➡️ (RIGHT). Mismatch!

❌ The Dumb Way (Brute Force)

The game screams "Wrong!" and wipes your memory clean to zero. You are forced to start entering the entire code from scratch starting at button #2. Total waste of effort!

✅ The Smart Way (KMP)

The game realizes: "Wait! In that failed attempt, the last three buttons they pressed were ⬆️ ⬆️ ⬇️. That is EXACTLY how the cheat code starts!" It magically saves those 3 buttons as a head start for your next attempt!

🔍 The "Aha!" Moment: Visualizing the Head Start

Why did the game let us keep 3 buttons? Notice how the end of what you just pressed matches the start of the target code:

What you typed:⬆️ ⬆️ ⬇️ ⬆️ ⬆️ ⬇️
Target Code:⬆️ ⬆️ ⬇️ ⬆️ ⬆️ ➡️

In algorithm terms, this is called matching a Suffix (the end of what you typed) with a Prefix (the start of the pattern). KMP builds a Fallback Table (called LPS) beforehand so it instantly knows these overlaps exist!

🔌 Connecting Back to Your Interactive Canvas Above

Right now, you are putting this exact superpower into action! You are searching for the Pattern "ABACABA" inside the Text "ABABACABACABA".

  • Watch the green LPS Array in the animation—that is KMP's pre-calculated cheat sheet!
  • When a mismatch happens on screen, notice how the green pattern doesn't just inch forward by 1; it instantly jumps ahead to align overlapping characters without re-reading the text!
Execution State SyncLine 0 Active
⚙ State Variables
text index (i)0
pattern (j)0
LPS len0
LPS[j-1]0
Time: O(N + M)Space: O(M)
LeetCode #28