Build a KMP Prefix Table
Build the KMP longest-prefix-suffix (LPS) table in one pass, falling back to lps[j - 1] after a mismatch instead of starting over.
The problem
Implement kmp_prefix_table(pattern) and return its LPS table, the first half of the KMP string-search algorithm. lps[i] is the length of the longest proper prefix of pattern[:i + 1] that is also a suffix of pattern[:i + 1]. Proper means shorter than the whole string, so lps[0] is always 0. Example: for "ababaca" the table is [0, 0, 1, 2, 3, 0, 1]. For "ababa" (up to index 4) the prefix "aba" is also a suffix, so lps[4] = 3. An empty pattern returns []. Build the table in a single pass, in O(len(pattern)) time.
Starter code
def kmp_prefix_table(pattern):
passPublic examples
pattern = "ababaca"gives[0, 0, 1, 2, 3, 0, 1]pattern = "aaaa"gives[0, 1, 2, 3]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
