Complete the code to initialize the prefix array with zeros.
lps = [[1]] * len(pattern)
The prefix array (lps) should be initialized with zeros to store the longest prefix suffix lengths.
Complete the code to update the length of the previous longest prefix suffix.
if pattern[i] == pattern[length]: length += [1]
When characters match, increase the length of the longest prefix suffix by 1.
Fix the error in the while loop condition to avoid infinite loops.
while i < len(text) and j < len(pattern): if text[i] == pattern[j]: i += 1 j += 1 else: if j != [1]: j = lps[j - 1] else: i += 1
The check should be if j is not zero before updating j to avoid negative indexing.
Fill both blanks to correctly compute the prefix array (lps) for the pattern.
while i < len(pattern): if pattern[i] == pattern[[1]]: length += 1 lps[i] = length i += 1 else: if length != 0: length = lps[[2]] else: lps[i] = 0 i += 1
Use 'length' to compare characters and 'length - 1' to update length when mismatch occurs.
Fill all three blanks to complete the KMP search function that returns all starting indices of pattern matches in text.
def kmp_search(text, pattern): lps = compute_lps(pattern) i = 0 j = 0 result = [] while i < len(text): if text[i] == pattern[j]: i += [1] j += [2] if j == len(pattern): result.append(i - j) j = lps[[3]] else: if j != 0: j = lps[j - 1] else: i += 1 return result
Increment i and j by 1 when characters match. Reset j to lps[j-1] after a full match.