28. Find the Index of the First Occurrence in a String ๐
Difficulty: Easy
- Tags: String
, Two Pointers
Description
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
.
Examples
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.
Constraints
The strings
haystack
andneedle
consist of lowercase English letters.
Solution ๐ก
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
.
Java
Time Complexity โณ
O(n * m): The time complexity is O(n * m), where
n
is the length of thehaystack
andm
is the length of theneedle
. For each starting index inhaystack
, we compare up tom
characters.
Space Complexity ๐พ
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 here.
Last updated