Given two strings, a haystack and a needle, return the index of the first position in the haystack where the needle appears as a contiguous substring, or -1 if the needle never occurs.
By convention, an empty needle is considered to match at index 0.
Example 1
Input: haystack = "hello", needle = "ll"
Output: 2
The substring "ll" begins at index 2 of "hello".
Example 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1
There is no place in "aaaaa" that lines up with "bba", so the search fails.
Constraints
1 ≤ haystack.length, needle.length ≤ 10^4haystack and needle consist of lowercase English letters.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI