Find the Index of the First Occurrence in a String
Given two strings haystack and needle, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Open official problem prompt ↗Locate the first position where the pattern needle sits inside haystack, in time linear in the combined length.
Like a detective who, after matching several clues then hitting a dead end, does not start the whole investigation over - they jump back only to the last point that could still fit the evidence gathered so far.
- Input
- haystack = "sadbutsad", needle = "sad"
- Output
- 0
- Why
- "sad" occurs at index 0 (and again at index 6), and the first occurrence is index 0.
1 <= haystack.length, needle.length <= 10^4haystack and needle consist of only lowercase English characters