Find the Index of the First Occurrence in a String
EasyStringsstring matching
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given two strings haystack and needle, return the smallest index i such that needle appears in haystack starting at position i. If needle does not occur anywhere in haystack, return -1.
Try not to rely on built-in substring search. A linear-time approach such as KMP is a good follow-up.
Examples
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
"sad" occurs at indices 0 and 6; the first is 0.
Input: haystack = "leetcode", needle = "leeto"
Output: -1
"leeto" is not a substring of "leetcode".
Constraints
- 1 <= haystack.length, needle.length <= 10^4
- haystack and needle consist of lowercase English letters
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.