Algorithms and Data Structures · Senior · Question 22 of 75

How does KMP achieve O(n + m) string search?

Explanation

For each position of the pattern, the prefix function stores the length of the longest proper prefix that's also a suffix. On a mismatch the pattern jumps by that amount, so the text pointer never moves back.

Further reading

Problem with a question

Algorithms and Data Structures · Senior · question 22

Test yourself

Take the Algorithms and Data Structures · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz