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 to 3 spell ana. Another copy starts at index 3 and overlaps it, but the first copy counts, so the answer is 1.
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 #1

Test #2

Test #3

Arguments

haystack = "bananarama"
needle = "ana"

Expected Output

1