Learn LPS / Ο array, practice it yourself, and then watch how KMP uses that information to search efficiently in O(n + m).
The whole motivation of KMP can be taught with one sentence: do not re-check what you already know. This tab shows that idea in four simple stages.
We matched several characters and then hit a mismatch.
Press Next to begin the guided story.
Step through pattern preprocessing and watch the fallback logic carefully.
Enter the Ο values yourself and check each index.
Use the LPS array during search and watch how pointers move.
Compare the number of character comparisons on the same input.
buildLPS(pattern):
lps[0] = 0
len = 0
i = 1
while i < m:
if pattern[i] == pattern[len]:
len++
lps[i] = len
i++
else:
if len != 0:
len = lps[len - 1]
else:
lps[i] = 0
i++
KMP(text, pattern):
buildLPS(pattern)
i = 0, j = 0
while i < n:
if text[i] == pattern[j]:
i++, j++
if j == m:
report match at i - j
j = lps[j - 1]
else if i < n and text[i] != pattern[j]:
if j != 0:
j = lps[j - 1]
else:
i++