Implementing KMP with detailed comments
The code computes the longest prefix suffix array to enable skipping previously matched characters during searching, avoiding backtracking in the text by using this array to reset the pattern index smartly after mismatches.
Here's a straightforward Python implementation of KMP with inline comments describing how the longest–prefix–suffix (LPS) array is built and how it is used to skip ahead in the text without backtracking:
def compute_lps(pattern):
"""
Compute the Longest Proper Prefix which is also Suffix (LPS) array for the pattern.
lps[i] is defined as the length of the longest proper prefix of pattern[0..i]
which is also a suffix of pattern[0..i].
"""
m = len(pattern)
lps = [0] * m # lps[0] is always 0 (a single character has no proper prefix/suffix)
length = 0 # length of the previous longest prefix-suffix
i = 1
while i < m:
if pattern[i] == pattern[length]:
# We have extended a previous prefix-suffix match
length += 1
lps[i] = length
i += 1
else:
if length != 0:
# Mismatch: fall back to the next shorter candidate prefix.
# This uses the lps of the previous position to avoid restarting from 0.
length = lps[length - 1]
# Note: we do not increment i here, we try to match pattern[i] with the shorter prefix
else:
# No proper prefix-suffix found for this position
lps[i] = 0
i += 1
return lps
def kmp_search(text, pattern):
"""
Generator that yields starting indices where pattern is found in text.
"""
n, m = len(text), len(pattern)
if m == 0:
return # empty pattern, nothing to search
lps = compute_lps(pattern)
i = 0 # index for text
j = 0 # index for pattern
while i < n:
if text[i] == pattern[j]:
# Characters match, advance both indices
i += 1
j += 1
if j == m:
# Entire pattern matched; report occurrence at i - m
yield i - m
# Prepare j for the next possible match
j = lps[j - 1]
else:
# Mismatch after j characters matched
if j != 0:
# Instead of moving the text index back, we consult lps.
# lps[j-1] tells us the length of the longest prefix of pattern
# that is also a suffix of the substring pattern[0..j-1].
# We can shift the pattern so that this prefix aligns with the last
# lps[j-1] characters of the matched text and continue matching from there.
# This effectively "skips ahead" in the text: i stays the same, j falls back.
j = lps[j - 1]
else:
# No prefix matched; move to the next character in the text
i += 1
# Example usage:
if __name__ == "__main__":
t = "ABABDABACDABABCABAB"
p = "ABABCABAB"
print(list(kmp_search(t, p))) # prints [10]
How the LPS array allows skipping
Suppose you've matched j characters of the pattern and encounter a mismatch at text[i] vs. pattern[j]. A naive search would backtrack the text index i to re-examine characters, but KMP keeps i where it is and uses the precomputed lps[j-1] to decide how far to "fall back" in the pattern.
The value lps[j-1] is the length of the longest proper prefix of the pattern that is also a suffix of the substring pattern[0..j-1] already matched. That means the last lps[j-1] characters of the matched text are equal to the first lps[j-1] characters of the pattern. By setting j = lps[j-1], we realign the pattern so that this known overlap is preserved and resume comparison at that point. No characters in the text are re-examined, so the search runs in linear time.