Find the Index of the First Occurrence in a String
You get two strings, a long haystack and a short needle. Return the index where the needle first appears in the haystack, or -1 if it never does. Our example: "bad" in "ecbbadfg" — the answer is 3.
- input
haystackandneedle: strings.- returns
- The index of the first occurrence of
needleinhaystack, or-1ifneedleis not part ofhaystack. - constraints
- 1 ≤ haystack.length ≤ 5000
- 1 ≤ needle.length ≤ 5000
- haystack, needle: lowercase English letters
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
function strStr(haystack, needle) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more sliding window problems
- 643Maximum Average Subarray IEasysolve
- 3Longest Substring Without Repeating CharactersMediumsolve
- 209Minimum Size Subarray SumMediumsolve
- 424Longest Repeating Character ReplacementMediumsolve
- 567Permutation in StringMediumsolve
- 76Minimum Window SubstringHardsolve
- 30Substring with Concatenation of All WordsHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.