Leetcode 28. Find the Index of the First Occurrence in a String
LeetCode 28: Find the Index of the First Occurrence in a String
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
Example 1:
haystack = "sadbutsad"
, needle = "sad"
0
Example 2:
haystack = "leetcode"
, needle = "leeto"
-1
needle
be an empty string?
needle
will always be a non-empty string.haystack
is an empty string but needle
is not?
-1
.We’ll use a sliding window approach to solve this problem:
needle
is greater than the length of haystack
, return -1
.haystack
from the start to a point where the remaining substring length is at least the length of needle
.haystack
of the same length as needle
and compare it with needle
.-1
.This approach ensures that we check each possible substring exactly once, resulting in an efficient runtime.
public class Solution {
public int strStr(String haystack, String needle) {
int haystackLength = haystack.length();
int needleLength = needle.length();
if (needleLength > haystackLength) {
return -1;
}
// Slide over the 'haystack' string
for (int i = 0; i <= haystackLength - needleLength; i++) {
// Check if the substring starting at i matches needle
if (haystack.substring(i, i + needleLength).equals(needle)) {
return i;
}
}
return -1;
}
}
The time complexity of this solution is ( O((n - m + 1) \cdot m) ), where ( n ) is the length of haystack
and ( m ) is the length of needle
. This is because in the worst-case scenario, we compare the substring of length m
with needle
( (n - m + 1) ) times.
haystack
up to ( (n - m + 1) ) times results in ( O(n - m + 1) ) iterations.So, multiplying these operations we get the overall time complexity as ( O((n - m + 1) \cdot m) ).
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?