Find the Index of the First Occurrence in a String - Problem

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.

This is a classic string matching problem where we need to find if one string exists as a substring within another string and return its starting position.

Input & Output

Example 1 — Basic Case
$ Input: haystack = "sadbutsad", needle = "sad"
Output: 0
💡 Note: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2 — Not Found
$ Input: haystack = "leetcode", needle = "leeto"
Output: -1
💡 Note: "leeto" did not occur in "leetcode", so we return -1.
Example 3 — Single Character
$ Input: haystack = "hello", needle = "ll"
Output: 2
💡 Note: "ll" occurs at index 2 in "hello", so we return 2.

Constraints

  • 1 ≤ haystack.length, needle.length ≤ 104
  • haystack and needle consist of only lowercase English characters.

Visualization

Tap to expand
Find First Occurrence: "sad" in "sadbutsad"haystack = "sadbutsad"needle = "sad"Position check:sadbutsad012345678✓ Match at index 0Result: 0
Understanding the Visualization
1
Input
Two strings: haystack to search in, needle to find
2
Search Process
Check each position in haystack for needle match
3
Output
Return index of first occurrence or -1 if not found
Key Takeaway
🎯 Key Insight: Check each position systematically until we find a complete match
Asked in
Facebook 25 Amazon 20 Microsoft 18 Google 15
95.0K Views
Medium Frequency
~15 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen