Implement strStr()
1 approach, code in every language
Problem description
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.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free