What is the time and space complexity of the following code to search a string inside other string, on finding, function should return the index of first occurrence,else -1.
I assume time complexity is O(m*n) where m is length of haystack and n is length of needle.
However, i searched for the the memory complexity of python slice and found this answer here - Time complexity of string slice , according to it it is O(n^2).
So what is the overall time and space complexity of the below function.
Can we improve it by using memoryview on haystack.?
class Solution:
def strStr(self, haystack, needle):
if haystack == needle or needle == "":
return 0
needle_len = len(needle)
haystack_len = len(haystack)
for i in range(0, haystack_len - needle_len + 1):
if needle == haystack[i:i+needle_len]:
return i
return -1