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 <= 104haystack and needle consist of only lowercase English characters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are searching for a specific short word inside a much longer piece of text by holding the short word against every possible spot in the text. The brute force strategy involves testing every single possible starting position in the text one by one to see if your short word matches the text starting at that exact spot.
Here's how the algorithm would work step-by-step:
def find_first_occurrence(haystack_text, needle_word):
# We limit the outer loop so we only check valid starting points where needle can fit
for start_index in range(len(haystack_text) - len(needle_word) + 1):
match_found = True
# We iterate through each character of the needle to verify the current window match
for needle_index in range(len(needle_word)):
if haystack_text[start_index + needle_index] != needle_word[needle_index]:
match_found = False
break
# If the inner loop finished without mismatches, we have found our exact starting index
if match_found:
return start_index
# Returning negative one indicates the needle does not exist anywhere within the haystack
return -1Instead of checking every single possible starting point one by one, the smartest approach looks ahead and uses clever shortcuts to skip unnecessary checks. It sets up a helper guide based on the target pattern so that whenever a mismatch happens, the search process can jump forward immediately instead of starting over from scratch.
Here's how the algorithm would work step-by-step:
class Solution:
def strStr(self, main_text: str, target_pattern: str) -> int:
if not target_pattern:
return 0
prefix_table = [0] * len(target_pattern)
pattern_index = 0
iterator_index = 1
# Build the reference map to track repeating character patterns.
while iterator_index < len(target_pattern):
if target_pattern[iterator_index] == target_pattern[pattern_index]:
pattern_index += 1
prefix_table[iterator_index] = pattern_index
iterator_index += 1
elif pattern_index > 0:
pattern_index = prefix_table[pattern_index - 1]
else:
prefix_table[iterator_index] = 0
iterator_index += 1
text_index = 0
pattern_index = 0
# Scan the main text while matching characters against the pattern.
while text_index < len(main_text):
if main_text[text_index] == target_pattern[pattern_index]:
text_index += 1
pattern_index += 1
if pattern_index == len(target_pattern):
return text_index - pattern_index
elif text_index < len(main_text) and main_text[text_index] != target_pattern[pattern_index]:
# Shift perspective forward using the reference map instead of restarting.
if pattern_index > 0:
pattern_index = prefix_table[pattern_index - 1]
else:
text_index += 1
return -1| Case | How to Handle |
|---|---|
| Needle is an empty string | Return zero immediately as per standard convention where an empty string is found at index zero. |
| Haystack is shorter than needle | Return a negative value immediately since a longer substring cannot exist inside a shorter string. |
| Needle and haystack are identical in length and content | The loop will check the entire haystack and successfully return index zero. |
| Needle appears multiple times inside haystack | Using a linear scan or standard search will naturally halt and return the starting index of the first occurrence. |
| Needle is not present in haystack | The algorithm will exhaust all valid starting positions and return a negative value representing absence. |
| Haystack and needle contain all identical characters | String comparison mechanics will correctly match the substring length and return the appropriate starting index. |
| Maximum sized strings approaching memory or time limits | Implement an efficient string matching algorithm like KMP or optimized sliding window to prevent time limit exceedance. |
| Null or uninitialized input strings | Check for null references at the beginning of the function and return a negative value to prevent runtime exceptions. |