Problem Description
Given two strings, needle and haystack, the task is to return the index of the first occurrence of needle in haystack. If needle is not present in haystack, then return -1.
Key Insights
- Search for a substring (needle) within a larger string (haystack).
- A straightforward approach is to iterate and compare potential starting positions.
- The naive approach checks each possible starting index in haystack, while more advanced techniques (like KMP) can improve efficiency, but the naive approach is often sufficient given the constraints.
- Special edge-case: if needle is an empty string (as typically defined in some similar problems) but here constraints guarantee positive length.
Space and Time Complexity
Time Complexity: O(n * m) in the worst case, where n is the length of haystack and m is the length of needle. Space Complexity: O(1) as no additional space is used.
Solution
The solution uses a brute force method with two pointers. We iterate over each possible starting position in haystack and check if the substring starting there matches the needle. If we find a match, we return the current index as the first occurrence. If no match is found after checking all possible positions, we return -1. This approach is simple and directly implements the problem's requirement.