Table of Contents
Task
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input:
haystack = "sadbutsad", needle = "sad"
Output:
0
Explanation:
"sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2:
Input:
haystack = "leetcode", needle = "leeto"
Output:
-1
Explanation:
"leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 104haystackandneedleconsist of only lowercase English characters.
this problem was taken from Leetcode
Solution
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    var match = 0;
    // Edge case: if needle is an empty string, return 0
    if (needle === "") {
        return 0;
    }
    // Get the lengths of both strings
    const haystackLen = haystack.length;
    const needleleLen = needle.length;
    
    // Iterate through the haystack string
    for (let i = 0; i <= haystackLen - needleleLen; i++) {
        var left = 0;
        while(left < needleleLen && haystack[left + i] == needle[left]) {
            left ++;
        }
        if(left == needleleLen) {
            return i;
        }
    }
    return -1;
};
Explanation:
- Edge Case: If 
needleis an empty string, the function immediately returns0. - Outer Loop: The outer loop iterates over each character in 
haystackwhere there is still enough remaining length to match theneedle(i <= haystackLen - needleLen). - Inner Loop: The inner loop checks if the substring of 
haystackstarting atimatchesneedle. It does this by comparing characters one-by-one. - Match Found: If a match is found (
j === needleLen), the starting indexiis returned. - No Match: If no match is found by the end of the loop, the function returns 
-1. 
This implementation mimics a basic substring search without using any built-in functions. The time complexity is O(n * m), where n is the length of haystack and m is the length of needle.