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.
Function Signature
def find_first_occurrence(haystack: str, needle: str) -> int:
Rules
-
Indices are 0-based.
-
Return the smallest
i
such that
haystack[i:i + len(needle)] == needle
. Occurrences may overlap, and only the first one matters.
-
Return
-1
when there is no such
i
, including when
needle
is longer than
haystack
.
Constraints
-
1 <= len(haystack), len(needle) <= 10⁴
-
haystack
and
needle
consist of only lowercase English characters.
Examples
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
"sad" occurs at index 0 and at index 6. The first occurrence is at index 0, so 0 is returned.
Input: haystack = "leetcode", needle = "leeto"
Output: -1
The four length-5 windows of "leetcode" are "leetc", "eetco", "etcod" and "tcode". None of them is "leeto", so -1 is returned.
Input: haystack = "abababcab", needle = "ababc"
Output: 2
The window starting at index 0 is "ababa", which fails on its fifth character. The window starting at index 2 is "ababc", so 2 is returned.