Implement strStr() Problem
Description
LeetCode Problem 28.
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
- 0 <= haystack.length, needle.length <= 5 * 10^4
- haystack and needle consist of only lower-case English characters.
Solution
Approach: Knuth-Morris-Pratt (KMP)
The direct way tries every start position in haystack and compares up to m characters there, which is O(n · m) in the worst case (for example haystack = "aaaa…a", needle = "aa…ab"). KMP finds the match in O(n + m) by never moving backwards in haystack: after a mismatch, it already knows how much of the needle still matches.
1. Precompute the lps table ("longest proper prefix that is also a suffix"). lps[i] is the length of the longest prefix of needle[0..i] that also ends at position i, not counting the whole string. For needle = "aabaaac":
needle: a a b a a a c
lps: 0 1 0 1 2 2 0
It is built by scanning needle against itself: length is the current matching prefix; on a mismatch, fall back to length = lps[length - 1] until the next character matches or length is 0.
2. Scan haystack with matched, the number of needle characters that match the text ending at the current position:
- while
matched > 0and the next characters differ, setmatched = lps[matched - 1]: the longest part of the current match that is still a prefix ofneedle; - if they are equal, increase
matched; - when
matched == m, the needle ends ati, so it starts ati - m + 1.
The fallback is what makes KMP correct: any shorter match that could still succeed must be a prefix of needle that is also a suffix of the part already matched, and lps gives the longest one, so no possible start position is skipped. An empty needle returns 0, as the problem asks.
Complexity: O(n + m) time, where n is the length of haystack and m the length of needle (each fallback undoes an earlier step forward, so the while loops run O(n + m) times in total), and O(m) extra space for lps.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(needle)
if m == 0:
return 0
# lps[i]: length of the longest proper prefix of needle[0..i] that is also a suffix of it.
lps = [0] * m
length = 0 # length of the current matching prefix
for i in range(1, m):
while length > 0 and needle[i] != needle[length]:
length = lps[length - 1] # fall back to the next shorter prefix that still matches
if needle[i] == needle[length]:
length += 1
lps[i] = length
matched = 0 # how many characters of needle match the text ending at haystack[i]
for i in range(len(haystack)):
while matched > 0 and haystack[i] != needle[matched]:
matched = lps[matched - 1] # keep the longest part of the match that can still be extended
if haystack[i] == needle[matched]:
matched += 1
if matched == m:
return i - m + 1 # the match ends at i, so it starts m - 1 characters earlier
return -1
Now write it from memory
Close the write-up and solve it yourself against the tests.