Find the Index of the First Occurrence in a String (LeetCode 28): Solution and Explanation
You are given a longer string haystack and a shorter string needle, and you must return the first index where needle appears inside haystack. If it never appears, return -1.
Watch it run step by step
Try your own input and write the code →Intuition
The natural way to think about this is to slide a window the size of needle across haystack. At each starting position you compare the window to needle character by character, and the first window that matches completely is the answer. There are n - m + 1 possible starting positions, and each comparison can take up to m steps, so the worst case is O(n × m). With the given constraints of a few thousand characters, that is perfectly fast.
The reference solution delegates this to the language's built-in search, haystack.find(needle) in Python, indexOf in Java and find in C++. Those routines implement exactly the sliding comparison, with extra tricks layered on top. CPython, for example, skips ahead using the last character of the needle and, in recent versions, switches to the two-way algorithm for longer needles, which runs in linear time. In an interview it is reasonable to use the library call and then explain what it does underneath.
If an interviewer asks you to avoid the library, write the window loop yourself. If they push further and ask about the worst case, the answer is the Knuth-Morris-Pratt algorithm. Its insight is that when a partial match fails, the characters you already matched tell you how far you can shift the needle without rechecking them. Precomputing a failure table for the needle in O(m) lets the scan over the haystack finish in O(n), for O(n + m) total.
Approach: Built-in substring search
- Call
haystack.find(needle), which looks for the first position where the whole needle matches. - Conceptually, the search tries each start index
ifrom 0 ton - m, comparinghaystack[i + k]withneedle[k]forkfrom 0 upward. - As soon as a character differs, that start index is abandoned and the search moves on to the next one.
- The first start index where all
mcharacters match is returned immediately. - If no window matches,
findreturns -1, which is exactly the value the problem asks for, so the result is returned as is.
Step-by-step example
haystack = "hello", needle = "ll"
- At index 0,
haystack[0]is 'h' andneedle[0]is 'l'. They differ, so move on. - At index 1, 'e' differs from 'l', so move on.
- At index 2, 'l' matches 'l', and the next pair
haystack[3]andneedle[1]are both 'l', so the whole needle matches. - The search stops and returns 2, the first index where "ll" appears.
Code: Python, Java, C++
1class Solution:
2 def strStr(self, haystack: str, needle: str) -> int:
3 return haystack.find(needle)1class Solution {
2 public int strStr(String haystack, String needle) {
3 return haystack.indexOf(needle);
4 }
5}1class Solution {
2public:
3 int strStr(string haystack, string needle) {
4 size_t pos = haystack.find(needle);
5 return pos == string::npos ? -1 : pos;
6 }
7};Time and space complexity
O(n × m)
In the worst case the sliding comparison checks up to m characters at each of the n - m + 1 start positions. Library implementations are usually much faster on real text, and some use linear-time algorithms internally, but O(n × m) is the safe bound to quote for the plain approach.
O(1)
The comparison works directly on the two input strings and needs only a couple of index variables.
Other approaches
Knuth-Morris-Pratt (time O(n + m), space O(m))
Build a longest-prefix-suffix table for the needle, then scan the haystack once. On a mismatch, the table tells you where in the needle to resume, so no haystack character is compared more than a constant number of times. Prefer it when a guaranteed linear bound matters.
Rabin-Karp rolling hash (time O(n + m) average, space O(1))
Hash the needle and every window of the haystack with a rolling hash that updates in O(1) per shift, and only compare characters when the hashes match. It is linear on average and extends nicely to searching for many patterns at once.
Common mistakes
- Looping the start index all the way to
n - 1. The last valid start isn - m, and going further either reads past the end of the haystack or wastes comparisons. - Forgetting to reset the inner index after a failed partial match in a handwritten loop. Each new start position must compare from the beginning of the needle.
- Writing KMP but advancing the haystack pointer on a mismatch when the needle pointer is not zero. You should only fall back in the needle, using the table, and keep the haystack position.
- Using a hash approach without verifying a match character by character, which can return a false positive on a collision.
Frequently asked questions
Is it OK to use indexOf or find in an interview for strStr?
Many interviewers accept it as a first answer, but most will then ask you to implement the search yourself. Be ready to write the window loop and to describe KMP for the worst case.
What is the time complexity of the brute force strStr?
O(n × m), because there are about n start positions and each may compare up to m characters. A haystack of all 'a' characters with a needle like "aaab" triggers that worst case.
When should I use KMP instead of brute force?
Use KMP when inputs are large or adversarial and you need a guaranteed O(n + m) bound. For short strings like those in this problem, the simple window comparison is clearer and fast enough.