28. Find the Index of the First Occurrence in a String ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: String
, Two Pointers
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:
Input:
Output:
Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2:
Input:
Output:
Explanation: "leeto" did not occur in "leetcode", so we return -1.
The strings haystack
and needle
consist of lowercase English letters.
To solve this problem manually (without using built-in methods like indexOf
), we can use a sliding window technique. We check each substring in haystack
of the same length as needle
and compare it with needle
. If a match is found, return the starting index. If no match is found, return -1
.
O(n * m): The time complexity is O(n * m), where n
is the length of the haystack
and m
is the length of the needle
. For each starting index in haystack
, we compare up to m
characters.
O(1): We only use constant space for variables, as no additional space is needed beyond the input strings.
You can find the full solution .