← switch

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

easy

Two Pointers · String · String Matching · Z Algorithm · Knuth–Morris–Pratt Algorithm · Boyer–Moore String-Search Algorithm

read the problem on leetcode →

first solved 13 Sept 2026

python
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(haystack)
        m = len(needle)

        for i in range(n - m + 1):
            if haystack[i:i + m] == needle:
                return i

        return -1