Find the Index of the First Occurrence in a String
Easy Advanced data structures and strings AI round
haystack and needle are two strings.
Find the first place where needle appears inside haystack as one run of consecutive characters.
Return the position of the first character of that run, counting from 0, or -1 if needle does not appear in haystack at all.
Example 1
Input: haystack = "bananarama", needle = "nara"
Output: 4
The letters at positions 4 to 7 of bananarama are n, a, r, a, so nara first appears at position 4, counting from 0. The n at position 2 is followed by a and n, which is not nara.
Example 2
Input: haystack = "the cat sat", needle = "cat"
Output: 4
Example 3
Input: haystack = "rain", needle = "sun"
Output: -1
Constraints
1 ≤ haystack.length ≤ 10⁵1 ≤ needle.length ≤ 10⁵- Both strings hold printable ASCII characters: letters, digits, symbols and spaces
- Capital and small letters are different characters
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
More Advanced data structures and strings
- Maximum Length of Repeated SubarrayAI round · Medium
- Repeated Substring PatternAI round · Easy
- Count of Smaller Numbers After SelfHard
- Reverse PairsHard
- Range Sum Query - MutableMedium