Prefix/Suffix
Prefix Function
Precomputing the Pi table for optimized jumping.
Time Complexity
O(M)
Space Complexity
O(M)
Interactive Visualization
Technical Guide
The Prefix Function (often called the Pi table) is the engine behind KMP. For every position in the pattern, it stores the length of the longest proper prefix that is also a suffix of that substring. This precomputation tells us exactly how much of the pattern we've already successfully matched even after a mismatch occurs, allowing us to skip ahead.
Logical Phases
- 1Initializing pi[0] = 0.
- 2Comparing the current character with the character after the current prefix.
- 3Backtracking through previous prefix lengths on mismatch.
- 4Storing the resulting lengths in an array of size M.
Implementation
if (p[k] === p[q]) k++;
pi[q] = k;Expert Pitfalls
Incorrectly including the entire string as a 'proper' prefix (k must be less than current length).