Knuth–Morris–Pratt String Search

medium
Unit 14 · Strings & BFS0/3 to milestone

Naive substring search is O(n·m) in the worst case ("aaaa...ab" in "aaaa...a"). KMP is O(n + m): it precomputes, for each prefix of the pattern, the length of the longest proper prefix that is also a suffix (the failure function, or LPS array), so it never re-examines text characters.

Implement:

  • lps(pattern): the failure function as a list
  • kmp_search(text, pattern): the start indices of all occurrences, including overlapping ones
  • shortest_period(s): the length of the smallest string p such that s is a prefix of p repeated many times ("abcabcab" → 3). Hint: it's len(s) - lps(s)[-1].

Don't use str.find, re or in for the search.

#strings#pattern-matching2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Knuth–Morris–Pratt String Search · TechGradify