Given two strings haystack and needle, return the index of the first occurrence of needle within haystack. If needle does not exist as a substring of haystack, return
Constraints:
haystack.length, needle.length
haystack and needle consist of only lowercase English characters
The key intuition behind this solution is to use a fixed-size sliding window of length equal to needle and slide it across haystack one character at a time, comparing the contents of each window against needle. As soon as a matching window is found, the starting index is returned immediately. If no match is found after exhausting all possible window positions,
Now, let’s look at the solution steps below:
Store the lengths of haystack and needle in haystackLen and needleLen, respectively.
Perform an early exit check if needleLen is greater than haystackLen, as needle cannot possibly be a substring. Return
Given two strings haystack and needle, return the index of the first occurrence of needle within haystack. If needle does not exist as a substring of haystack, return
Constraints:
haystack.length, needle.length
haystack and needle consist of only lowercase English characters
The key intuition behind this solution is to use a fixed-size sliding window of length equal to needle and slide it across haystack one character at a time, comparing the contents of each window against needle. As soon as a matching window is found, the starting index is returned immediately. If no match is found after exhausting all possible window positions,
Now, let’s look at the solution steps below:
Store the lengths of haystack and needle in haystackLen and needleLen, respectively.
Perform an early exit check if needleLen is greater than haystackLen, as needle cannot possibly be a substring. Return