Explain the KMP prefix (failure) table and how KMP matches in linear time.
HardString algorithms
Technical
Content review
Report an errorNot yet reviewed
Show model answer
For each position i of the pattern, the prefix table stores the length of the longest proper prefix of pattern[0..i] that is also a suffix of it. It is built in O(m) by extending the current border when the next characters match and falling back through the table when they do not.
During matching, when a mismatch happens after j matched characters, those j characters are already known, so instead of moving the text pointer back, KMP sets j to table[j − 1] and keeps going. The text pointer never moves backward, so matching is O(n) and the whole algorithm is O(n + m) time with O(m) extra space, independent of the alphabet.
What interviewers listen for
- Text pointer never backs up
- Table construction is itself a KMP run of the pattern against itself