Problem
Return the first index where needle appears in haystack, or -1 if it does not appear.
Original: LeetCode 28: Find the Index of the First Occurrence in a String.
Examples
Example 1
`haystack = "sadbutsad", needle = "sad"``0`Example 2
`haystack = "leetcode", needle = "leeto"``-1`Constraints
1 <= haystack.length, needle.length <= 10^4haystackandneedleconsist of only lowercase English characters.
Hints
Hint 1
This is substring search, the same idea as
indexOf. If needle is empty, the conventional answer is 0, but official cases focus on non-empty strings.Hint 2
Exact string matching: a sliding comparison at each offset, or a linear-time prefix table.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. For each start i from 0 to n-m, compare m characters. Stop at the first full match.
Optimal. The brute-force scan is acceptable for an interview unless they ask for a linear algorithm. Knuth-Morris-Pratt (or Rabin-Karp) is the upgrade: preprocess the needle in O(m) and scan the haystack in O(n).
Alternative. Calling the language's built-in indexOf or str.find is fine to mention, but you should still be able to write the loops.
Complexity
- Time
- O(n m)
The two-loop search is O(n m) time and O(1) extra space. KMP is O(n + m) time and O(m) space.
- Space
- O(1)
Code
def str_str(haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
if m == 0:
return 0
for i in range(n - m + 1):
if haystack[i:i + m] == needle:
return i
return -1
if __name__ == "__main__":
assert str_str("sadbutsad", "sad") == 0
assert str_str("leetcode", "leeto") == -1
print("ok")public class FindFirstOccurrence {
static int strStr(String haystack, String needle) {
int n = haystack.length(), m = needle.length();
if (m == 0) return 0;
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;
}
public static void main(String[] args) {
if (strStr("sadbutsad", "sad") != 0) throw new AssertionError();
if (strStr("leetcode", "leeto") != -1) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "sadbutsad" with "sad" returns 0, and "leetcode" with "leeto" returns -1.
- If the needle is longer than the haystack, the answer is -1.
- Overlapping occurrences: you still return the first start index.
Follow-ups
- Implement KMP: build the longest-prefix-suffix table of the needle, then never move the haystack index backwards on a mismatch.
Interview script
"I start with the obvious scan: try every start position and compare the needle. That is O(n m). If they want linear time, I would build a KMP prefix table so each character of the haystack is examined a constant number of times."
Source: LeetCode 28: Find the Index of the First Occurrence in a String