Efficient
KMP Algorithm
Linear time pattern matching using the prefix function.
Time Complexity
O(N + M)
Space Complexity
O(M)
Interactive Visualization
Technical Guide
Knuth-Morris-Pratt (KMP) is the first linear-time string matching algorithm discovered. It uses the precomputed Prefix Function to ensure that the pointer in the main text *never* moves backward. When a mismatch occurs, the algorithm looks up the Prefix Table to see what's the next best alignment, effectively 'jumping' the pattern across the text.
Logical Phases
- 1Computing the Prefix Table (Pi) for the pattern in O(M).
- 2Scanning the text once with pointer 'i' and pattern with pointer 'q'.
- 3On mismatch, setting q = pi[q-1] instead of resetting i.
- 4Completing the search in exactly O(N + M) time.
Implementation
while (q > 0 && p[q] !== t[i]) q = pi[q-1];Expert Pitfalls
Off-by-one errors when indexing the Pi table after a mismatch.