243. Find the Index of the First Occurrence

MediumStringString

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. An empty needle returns 0. Input: '"haystack", "needle"'.

Input: '"haystack", "needle"'.

Output: Integer — index or -1.

Examples

Example 1
Input: "sadbutsad", "sad"
Output: 0
Explanation: First 'sad' at index 0.
Example 2
Input: "leetcode", "leeto"
Output: -1
Explanation: Not present.
Example 3
Input: "hello", "ll"
Output: 2
Explanation: 'll' at index 2.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →