DSA problem
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.
This is the classic substring-search (pattern-matching) problem. You must locate the first starting position where the entire needle string appears contiguously inside haystack. Both strings consist of lowercase English letters, and needle is guaranteed to be non-empty, so the answer is the smallest valid index or -1 when no match exists.
Examples
Example 1
Input:
haystack = "sadbutsad", needle = "sad"Output:
0Explanation: "sad" occurs at index 0 and also at index 6. The first occurrence is at index 0, so we return 0.
Example 2
Input:
haystack = "leetcode", needle = "leeto"Output:
-1Explanation: "leeto" never occurs as a contiguous substring of "leetcode", so the function returns -1.
Example 3
Input:
haystack = "abc", needle = "c"Output:
2Explanation: The single-character needle "c" first appears at index 2.
Constraints
- 1 <= haystack.length, needle.length <= 10^4
- haystack and needle consist of only lowercase English characters.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.