Implement strStr()

Problem

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

For example:

Input: haystack = "hello", needle = "ll"
Output: 2
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Input: haystack = "", needle = ""
Output: 0

Solution

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        
        length = len(needle)
        if needle == "":
            return 0
        
        for i in range(len(haystack)):
            if haystack[i:i+length] == needle:
                return i
        return -1
        
#Time: O(n)
#Space: O(1)

#Its just substring matching

Last updated