
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).
1def strStr(haystack: str, needle: str) -> int:
2 m, n = len(haystack), len(needle)
3 if n == 0:
4 return 0
5 for i in range(m - n + 1):
6 if haystack[i:i+n] == needle:
7 return i
8 return -1
9
10print(strStr("sadbutsad", "sad")) # Output: 0This Python solution uses slicing to compare parts of the haystack 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.
1
This JavaScript implementation efficiently searches for the needle using the KMP algorithm with an LPS array.