SDE & MLE Prep

28. Find the Index of the First Occurrence in a String

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