Find the Index of the First Occurrence in a String

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 <= 104
  • haystack and needle consist 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:

  1. Edge Case: If needle is an empty string, the function immediately returns 0.
  2. Outer Loop: The outer loop iterates over each character in haystack where there is still enough remaining length to match the needle (i <= haystackLen - needleLen).
  3. Inner Loop: The inner loop checks if the substring of haystack starting at i matches needle. It does this by comparing characters one-by-one.
  4. Match Found: If a match is found (j === needleLen), the starting index i is returned.
  5. 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.

Leave a Reply