You are a detective searching for clues! Given two strings, needle and haystack, your mission is to find where the first occurrence of the needle appears within the haystack.
This is a classic string matching problem that appears frequently in coding interviews. You need to return the index (0-based) of the first character where needle starts in haystack. If the needle is not found anywhere in the haystack, return -1.
Example: If haystack = "hello world" and needle = "world", you should return 6 because "world" starts at index 6.
This problem tests your understanding of string manipulation, pattern matching, and algorithm optimization. While it seems simple, there are multiple approaches ranging from brute force to advanced string matching algorithms!
Input & Output
Visualization
Time & Space Complexity
Built-in functions typically use optimized algorithms with linear time complexity
Built-in functions are space-optimized
Constraints
- 1 โค haystack.length, needle.length โค 104
- haystack and needle consist of only lowercase English characters
- needle will not be longer than haystack