
Sponsored
Sponsored
The brute force approach involves iterating over each possible starting position of the needle in the haystack and checking if the substring from that position matches the needle.
Time Complexity: O((m-n+1)*n), where m is the length of haystack and n is the length of needle.
Space Complexity: O(1).
This JavaScript solution examines each substring of the haystack to check for a match with the needle.
The KMP (Knuth-Morris-Pratt) algorithm is a more efficient string-searching algorithm. It preprocesses the needle to create a longest prefix-suffix (LPS) array, which is used to skip unnecessary comparisons while searching in the haystack.
Time Complexity: O(m + n), where m is the length of haystack and n is the length of needle.
Space Complexity: O(n), due to the LPS array.
1def strStr(haystack: str, needle: str) -> int:
2 if not needle:
3 return 0
4 def computeLPS(pattern):
5 lps = [0] * len(pattern)
6 length = 0
7 i = 1
8 while i < len(pattern):
9 if pattern[i] == pattern[length]:
10 length += 1
11 lps[i] = length
12 i += 1
13 else:
14 if length != 0:
15 length = lps[length - 1]
16 else:
17 lps[i] = 0
18 i += 1
19 return lps
20 lps = computeLPS(needle)
21 i = j = 0
22 while i < len(haystack):
23 if haystack[i] == needle[j]:
24 i += 1
25 j += 1
26 if j == len(needle):
27 return i - j
28 elif i < len(haystack) and haystack[i] != needle[j]:
29 if j != 0:
30 j = lps[j - 1]
31 else:
32 i += 1
33 return -1
34
35print(strStr("sadbutsad", "sad")) # Output: 0The Python code implements the KMP algorithm, using an LPS array to efficiently find the needle in the haystack.