Find the Index of the First Occurrence in a String
Given two strings haystack and needle, return the index of the first occurrence of needle in haystack.
If needle does not occur in haystack, return:
-1
Example
Input:
haystack = "sadbutsad"
needle = "sad"
The first occurrence of "sad" starts at index 0.
Output
0
Main Idea
We need to check every possible starting position in haystack.
For each position:
- Check whether there are enough characters remaining.
- Compare the substring starting at that position with needle.
- If all characters match, return that index.
- If no position matches, return -1.
Example
haystack = "hello"
needle = "ll"
Check:
h e → no
e l → no
l l → match
Therefore:
Answer = 2
Important Point
We need the first occurrence, so we return immediately when a match is found.
Example 1
Input
sadbutsad sad
Output
0
Explanation
"sad" first appears at index 0.
Example 2
Input
leetcode leeto
Output
-1
Explanation
"leeto" does not occur in "leetcode".
Constraints
Hints:
Hint 1
Try every possible starting position in haystack.
Hint 2
A match is possible only while enough characters remain for the complete needle.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 17, 2026
Last updated
Aug 18, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output