Back to DSA sheet

Find The Index of The First Occurrence in a String

EasyArrays

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

Input format (stdin): the first line is haystack, the second line is needle. Output the index or -1.

Examples
Input: sadbutsad sad
Output: 0
needle 'sad' first appears at index 0.
Input: leetcode leeto
Output: -1
'leeto' never appears.
Constraints
  • 1 <= |haystack|, |needle| <= 10^4
  • Lowercase English letters
Sheets
NeetCode 250
find-the-index-of-the-first-occurrence-in-a-string.cpp3 sample tests
Loading editor
Test results

Run the sample tests to check your solution against expected output.

Custom input (stdin)
Output

Run your code to see its output.