Find the Index of the First Occurrence in a String

Easy Advanced data structures and strings AI round

haystack and needle are two strings.

Find the first place where needle appears inside haystack as one run of consecutive characters.

Return the position of the first character of that run, counting from 0, or -1 if needle does not appear in haystack at all.

Example 1

Input: haystack = "bananarama", needle = "nara"
Output: 4

The letters at positions 4 to 7 of bananarama are n, a, r, a, so nara first appears at position 4, counting from 0. The n at position 2 is followed by a and n, which is not nara.

Example 2

Input: haystack = "the cat sat", needle = "cat"
Output: 4

Example 3

Input: haystack = "rain", needle = "sun"
Output: -1

Constraints

  • 1 ≤ haystack.length ≤ 10⁵
  • 1 ≤ needle.length ≤ 10⁵
  • Both strings hold printable ASCII characters: letters, digits, symbols and spaces
  • Capital and small letters are different characters

More Advanced data structures and strings

All Advanced data structures and strings problems