
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).
1function strStr(haystack, needle) {
2 let m = haystack.length;
3 let n = needle.length;
4 if (n === 0) return 0;
5 for (let i = 0; i <= m - n; i++) {
6 let j = 0;
7 for (; j < n; j++) {
8 if (haystack[i + j] !== needle[j])
9 break;
10 }
11 if (j === n) return i;
12 }
13 return -1;
14}
15
16console.log(strStr("sadbutsad", "sad")); // Output: 0This 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.
This C solution uses the KMP algorithm, which preprocesses the needle to create an LPS array, reducing the number of comparisons required.