KMP Notes Flashcards
1
Q
KMP Main Points
A
- Depends on LPS Array (Longest prefix which is also suffix)
- When there is mismatch in the search string against our pattern then we need not go to the beginning of the search string to again match - worst case is improved here.
- Now, where do we go when there is mismatch, since there was everything matching before this mismatch so we can move back to some point where match can happen before - which is when the prefix and suffix are same.
- If we move to some previous point where the prefix and suffix are same then we do not need to match that prefix. Ex. if we have already matched …..abc and there is mismatch after this then we should go to the largest matching prefix before.
- Start matching again from here. Again repeat from 2.
2
Q
Where to go from mismatch
A
To the end of largest prefix which matches before mismatch
3
Q
What to do when reached prefix end after mismatch
A
Try to match again the mismatches. If they match then we need not match something before than this and proceed forward.
4
Q
What is optimization ?
A
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.
5
Q
Time Complexity
A
O(n + m)
6
Q
Space Complexity
A
O(p)