KMP Main Points
Where to go from mismatch
To the end of largest prefix which matches before mismatch
What to do when reached prefix end after mismatch
Try to match again the mismatches. If they match then we need not match something before than this and proceed forward.
What is optimization ?
We never match the string which we are already sure of. This surity comes from LPS values, just go back into the pattern where the possible match is possible not in beginning.
In naive algo the failure pushes the pattern to match again while in kmp we go to the point in pattern where the mismatch can be replicated.
Time Complexity
O(n + m)
Space Complexity
O(p)