[Verse 1]
When you're searching through a string for a pattern that you seek
Brute force checking every spot makes your algorithm weak
Moving one by one is slow when mismatches appear
But there's a smarter way to go, let me make it crystal clear
[Chorus]
KMP, don't restart from scratch
Build a table, find the match
Longest prefix suffix same
That's the KMP game
Skip ahead when patterns fail
Let the preprocessing tell the tale
Linear time is what we gain
KMP breaks the searching chain
[Verse 2]
First we build the failure function, scan the pattern left to right
When characters repeat themselves, we store that insight
If we match then hit a wall, don't go back to square one
Use the table, make the call, jump ahead until we're done
[Chorus]
KMP, don't restart from scratch
Build a table, find the match
Longest prefix suffix same
That's the KMP game
Skip ahead when patterns fail
Let the preprocessing tell the tale
Linear time is what we gain
KMP breaks the searching chain
[Verse 3]
Pattern A-B-A-B gives us values zero one zero three
Each position tells us how far back in history
When we fail at position four, we don't start from the beginning
Jump to where the pattern's core shows us we're still winning
[Bridge]
Preprocessing takes some time but searching flies so fast
O of n plus m combined, efficiency that lasts
While naive search quadratic might leave your program hanging
KMP stays logarithmic, keeps your algorithm banging
[Chorus]
KMP, don't restart from scratch
Build a table, find the match
Longest prefix suffix same
That's the KMP game
Skip ahead when patterns fail
Let the preprocessing tell the tale
Linear time is what we gain
KMP breaks the searching chain
[Outro]
From Knuth and Morris-Pratt, this wisdom they bestowed
Smart string matching is the path, now you know the code
When patterns hide in lengthy text, don't search like a fool
KMP algorithm's next level searching tool