Find the Index of the First Occurrence in a String Solution
Find the Index of the First Occurrence in a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript.
Find the Index of the First Occurrence in a String is an easy coding problem on strings and two pointers, asked in Dropbox interviews.
- Difficulty: Easy
- Topics: Strings, Two Pointers
- Asked at: Dropbox
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
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.
Example 1
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Example 2
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Constraints
1 <= haystack.length <= 401 <= needle.length <= 10Lowercase English letters.
Hints for Find the Index of the First Occurrence in a String
Hint 1
Try every start position and compare needle character by character.
Hint 2
You can stop a comparison at the first mismatch.
How to solve Find the Index of the First Occurrence in a String
Try every position in haystack where needle could start, and compare character by character from there — bailing out at the first mismatch. Only starts with enough room left are worth trying, which bounds the outer loop.
Approach
- Let
nandmbe the two lengths; ifm > nthere is no match. - For each start
ifrom0ton - m, compareneedle[j]withhaystack[i + j]. - Abandon the start at the first mismatch.
- If all
mcharacters match, returni. - Return
-1when no start works.
Why it works
Any occurrence begins at some index with at least m characters remaining, so scanning starts in increasing order and returning the first success gives the leftmost occurrence by construction. Early exit on a mismatch is what keeps the average cost near O(n) even though the worst case is O(n · m). KMP achieves a guaranteed O(n + m) by precomputing how far to shift after a mismatch instead of restarting at the next index.
Complexity
- Time —
O(n · m) worst case - Space —
O(1)
Pitfalls
- Bound the outer loop at
n - m, or the inner comparison reads past the end. - Return the start index, not the end.
- Return the first match; later ones are irrelevant.
- Handle
m > nbefore looping, since the bound would otherwise be negative.
Reference solution
Python
def strStr(haystack: str, needle: str) -> int:
return haystack.find(needle)Java
public static int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m > n) return -1;
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && haystack.charAt(i + j) == needle.charAt(j)) j++;
if (j == m) return i;
}
return -1;
}C++
int strStr(string haystack, string needle) {
int n = (int) haystack.size(), m = (int) needle.size();
if (m > n) return -1;
for (int i = 0; i + m <= n; i++) {
int j = 0;
while (j < m && haystack[i + j] == needle[j]) j++;
if (j == m) return i;
}
return -1;
}JavaScript
var strStr = function(haystack, needle) {
return haystack.indexOf(needle);
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Two Pointers Technique