28. Find the Index of the First Occurrence in a String
Asked at 16Microsoft58Bloomberg56Google56Amazon56Apple53Meta51Cognizant57Pocket Gems100tcs67Capgemini62Zoho60Qualcomm58Expedia54PayPal42Infosys30Yandex28
Problem
Return the index of the first occurrence of needle in haystack, or -1 if it doesn't occur.
Example: haystack = "sadbutsad", needle = "sad" → 0; haystack = "leetcode", needle = "leeto" → -1
Constraints: lengths ≤ 10⁴.
The brute force (try every start, compare up to m chars) is O(n·m) and fine for the given limits — say so, then offer KMP for O(n + m): precompute lps[i] = length of the longest proper prefix of needle[:i+1] that is also its suffix. On a mismatch, fall back to lps[k-1] instead of restarting, so the haystack pointer never moves backwards.
needle = "aab" lps = [0, 1, 0]
haystack a a a a a b
^ mismatch at needle[2] after "aa" -> k = lps[1] = 1, keep i
Complexity: O(n + m) time, O(m) space.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
lps, k = [0] * len(needle), 0
for i in range(1, len(needle)):
while k and needle[i] != needle[k]:
k = lps[k - 1]
if needle[i] == needle[k]:
k += 1
lps[i] = k
k = 0
for i, ch in enumerate(haystack):
while k and ch != needle[k]:
k = lps[k - 1]
if ch == needle[k]:
k += 1
if k == len(needle):
return i - k + 1
return -1
assert Solution().strStr("sadbutsad", "sad") == 0
assert Solution().strStr("leetcode", "leeto") == -1
assert Solution().strStr("aaaaab", "aab") == 3
assert Solution().strStr("mississippi", "issip") == 4
assert Solution().strStr("a", "a") == 0
assert Solution().strStr("abc", "c") == 2
class Solution {
public int strStr(String haystack, String needle) {
int m = needle.length();
int[] lps = new int[m];
for (int i = 1, k = 0; i < m; i++) {
while (k > 0 && needle.charAt(i) != needle.charAt(k)) k = lps[k - 1];
if (needle.charAt(i) == needle.charAt(k)) k++;
lps[i] = k;
}
for (int i = 0, k = 0; i < haystack.length(); i++) {
while (k > 0 && haystack.charAt(i) != needle.charAt(k)) k = lps[k - 1];
if (haystack.charAt(i) == needle.charAt(k) && ++k == m) return i - m + 1;
}
return -1;
}
}
func strStr(haystack string, needle string) int {
lps, k := make([]int, len(needle)), 0 // KMP failure function
for i := 1; i < len(needle); i++ {
for k > 0 && needle[i] != needle[k] {
k = lps[k-1]
}
if needle[i] == needle[k] {
k++
}
lps[i] = k
}
k = 0
for i := 0; i < len(haystack); i++ {
for k > 0 && haystack[i] != needle[k] {
k = lps[k-1]
}
if haystack[i] == needle[k] {
k++
if k == len(needle) {
return i - k + 1
}
}
}
return -1
}