You need to implement a function strStr(haystack: str, needle: str) -> int
that finds the first occurrence of the substring needle
in the string haystack
. If needle
is an empty string, return 0. If needle
is not present in haystack
, return -1.
haystack
and needle
are empty?
needle
is an empty string.We’ll start with a straightforward approach known as the “Sliding Window” or “Two-pointer” technique.
needle
is empty, return 0.haystack
with a window size equal to the length of needle
.haystack
matches needle
.Using this approach ensures we check each possible starting position in the haystack
string, verifying if needle
begins there.
n
be the length of haystack
and m
be the length of needle
.n - m + 1
starting positions in haystack
, and each comparison takes O(m)
time.O(n * m)
.Now, let’s implement this in Python.
def strStr(haystack: str, needle: str) -> int:
# If needle is an empty string
if not needle:
return 0
# Lengths of haystack and needle
n = len(haystack)
m = len(needle)
# Loop through haystack with a window of size m
for i in range(n - m + 1):
# Check if the substring of length m starting at i matches needle
if haystack[i:i + m] == needle:
return i
# If no match is found, return -1
return -1
needle
is empty, return 0 immediately.for i in range(n - m + 1)
ensures we don’t go out of bounds while checking substrings of length m
in haystack
.haystack[i:i + m]
to extract the current window and compare it directly with needle
.i
.This solution is straightforward and adheres closely to the problem’s requirements. Let me know if you need any further explanations or optimizations!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?