Back to problems Sign in to unlock
Leetcode
Easy
Strings
Arrays
Google
Find The Index Of The First Occurrence In A String
Find the first position where one string appears as a substring inside another string.
Acceptance 85%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement
Given two strings, haystack and needle, return the index of the first occurrence of needle in haystack. If needle does not appear in haystack, return -1.
The match must be contiguous and exact. If needle is empty, the answer is 0 by convention.
Input Format
- A string
haystack - A string
needle
Output Format
- Return a single integer: the first index where
needlestarts inhaystack, or-1if it does not occur
Constraints
- 0 <= |haystack|, |needle| <=
- Strings contain arbitrary lowercase or ASCII characters depending on platform variant
- The answer fits in a 32-bit signed integer
Examples
Sample cases returned by the problem API.
Example 1
Input
haystack = "sadbutsad", needle = "sad"
Output
0
Explanation
The substring "sad" appears at index 0 and again later, but we return the first occurrence.
Example 2
Input
haystack = "leetcode", needle = "leeto"
Output
-1
Explanation
The string "leeto" does not occur as a contiguous substring of "leetcode".
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.