Skip to main content

Find the Index of the First Occurrence

EasyString

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:

Searching 'sadbutsad' for 'sad': found at index 0 (s-a-d-b...) and index 6 (s-a-d). Returning the first occurrence: 0.

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 and sharpen your skills for technical interviews.