Find the Index of the First Occurrence in a String

Easy#28fixed size

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
haystack and needle: strings.
returns
The index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
constraints
  • 1 ≤ haystack.length ≤ 5000
  • 1 ≤ needle.length ≤ 5000
  • haystack, needle: lowercase English letters
our 13 tests keep to them
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

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more sliding window problems

Pattern “Sliding window” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.