First Occurrence in String
Given two strings haystack and needle, return the index of the first (leftmost) position at which needle appears inside haystack as a contiguous substring, or -1 if needle never appears. The matched characters must be adjacent and in order; the returned index is the starting position of that match.
- 1 <= haystack.length, needle.length <= 10โด
- haystack and needle consist of lowercase English letters only
haystack = "sadbutsad", needle = "sad"0haystack = "aaabaaa", needle = "aab"1haystack = "leetcode", needle = "leeto"-1Finding the first occurrence of a "needle" in a "haystack" is a classic pattern-matching task. We search the larger string from left to right, looking for the exact starting position where the entire needle appears.
The most intuitive way to solve this is using a Sliding Window. Imagine a window exactly the size of the needle. We place it at the very beginning of the haystack and check if the characters inside the window match our target. If they don't, we slide the window forward by one character and check again.
We repeat this until either:
1. We find a perfect match (and return the current starting index).
2. We reach the point where the remaining haystack characters are fewer than the needle length (and return -1).
In modern programming, instead of manually checking characters with nested loops, we compare whole "slices" of the string. This is both more readable and highly efficient at the language level.
h_len, n_len = len(haystack), len(needle)
# Loop through every possible starting position
for i in range(h_len - n_len + 1):
# Take a 'slice' of the haystack and compare
if haystack[i : i + n_len] == needle:
return i
return -1sliding window
Scanning index 0... Comparing "SAD" with "BUT".