Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack. If needle is not part of haystack, return -1.

Example 1
Inputhaystack = "sadbutsad", needle = "sad"
Output0
The substring "sad" first appears in "sadbutsad" starting at index 0.
Example 2
Inputhaystack = "leetcode", needle = "leeto"
Output-1
The substring "leeto" does not appear in "leetcode", so the result is -1.

Constraints

  • 1 <= haystack.length, needle.length <= 10^4
  • haystack and needle consist of only lowercase English characters.

Asked at 17 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate