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 in String INPUT haystack = "sadbutsad" s a d b u t s a d 0 1 2 3 4 5 6 7 8 needle = "sad" s a d Input Values haystack: "sadbutsad" needle: "sad" len(haystack): 9 len(needle): 3 ALGORITHM STEPS 1 Use Built-in Method Call str.find() or indexOf() 2 Internal Comparison Method scans haystack 3 Match at Index 0 "sad" found at position 0 4 Return Result Return index 0 Matching Process i=0: sad == sad [OK] OK Match found! Return index: 0 FINAL RESULT Found at Index 0 s a d b u t s a d First Match Output 0 OK - Match Found! "sad" starts at index 0 Key Insight: Built-in string methods like find(), indexOf(), or strStr() use optimized algorithms internally. For production code, these are preferred. Returns -1 if needle is not found in haystack. TutorialsPoint - Find the Index of the First Occurrence in a String | Built-in String Search
Asked in
Facebook 25 Amazon 20 Microsoft 18 Google 15
95.1K 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