Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

51. Find the Index of the First Occurrence in a String

EasyDay 16 of 60Strings

You are given two strings, haystack and needle. Return the index where needle first appears inside haystack. If needle never appears, return -1.

Example 1
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
"sad" appears at index 0 and again at index 6. The first one wins.
Example 2
Input: haystack = "leetcode", needle = "leeto"
Output: -1
"leeto" is not a substring of "leetcode".
Constraints
  • 1 <= haystack.length, needle.length <= 10^4
  • Both strings contain only lowercase English letters
Hints
Frequently asked at: Microsoft, Amazon, Meta, Paytm
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min