Find the Index of the First Occurrence

Easy

Description

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

Examples

Input:haystack = "sadbutsad", needle = "sad"
Output:0
Explanation:

"sad" occurs at index 0 and 6.

Input:haystack = "programming", needle = "gram"
Output:3
Explanation:

"gram" occurs at index 3 in "programming". The substring match starts at position 3: p-r-o-g-r-a-m-m-i-n-g.

Input:haystack = "hello", needle = "world"
Output:-1
Explanation:

"world" does not appear anywhere in "hello", so the result is -1.

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!