Menu
CoddyTech

Find the First Occurrence in a String

You get two strings, haystack and needle. Return the index in haystack where the first copy of needle starts, counting from 0. If needle never appears in haystack, return -1. Write the search yourself instead of calling a built-in substring search such as find or indexOf.

Function

strStr(haystack: string, needle: string) → integer
haystackstring
the text to search in
needlestring
the string to look for
Returnsinteger
the index where the first copy of needle starts, or -1 if there is none

Constraints

  • 1 ≤ haystack.length ≤ 5 × 104
  • 1 ≤ needle.length ≤ 5 × 104
  • Both strings contain only lowercase English letters.
  • needle may be longer than haystack. Then it cannot appear, and the answer is -1.

Examples

Input
haystack = "bananarama"needle = "ana"
Output
1
Explanation
The letters at indices 1, 2 and 3 spell ana. A second copy starts at index 3 and overlaps the first one, but the answer is the first copy, so it is 1.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

Can you return every index where needle starts, overlapping copies included, still in O(n + m) time?

Reset code
def strStr(haystack, needle):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

haystack = "bananarama"
needle = "ana"

Expected

1