Introduction
The Implement strStr() problem involves finding the first occurrence of a substring inside another string.
Given:
- a string haystack
- a string needle
the task is to:
- return the starting index
of the first occurrence of needle
inside haystack
If substring does not exist:
- return -1
This problem helps in understanding:
- pattern matching
- substring comparison
- traversal techniques
- sliding window concepts
Example
Input:haystack = "hello"needle = "ll"
Output: 2
Explanation:
"ll" starts at index 2.
Input: haystack = "abcdef" needle = "gh"
Output: -1
Explanation: Substring does not exist.
Constraints
1 <= haystack.length,needle.length <= 10^4
haystack and needle
contain lowercase English letters
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Check every possible starting index
- Compare substring characters one by one
- Return matching index
This approach directly follows the problem statement.
Steps
- Traverse possible starting positions.
- Compare substring characters.
- If all characters match:
- return index
- Otherwise continue traversal.
- Return -1 if no match exists.
Dry Run
Input:haystack = "hello"needle = "ll"
Check index 0: "he" Not matching
Check index 1:
"el"
Not matching
Check index 2: "ll" Match found
Final Result: 2
Brute Force Code
Complexity Analysis
Time Complexity: O(n * m)Explanation:
Substring comparison is performed
for every possible position.
Space Complexity: O(1) Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Substring Comparison)
Explanation
The optimized solution uses direct substring extraction.
The idea is:
- Extract substring of needle length
- Compare directly with needle
- Return matching index
This provides cleaner implementation.
Steps
- Traverse possible positions.
- Extract substring.
- Compare with needle.
- Return matching index.
- Return -1 otherwise.
Dry Run
Input:haystack = "hello"needle = "ll"
Extract substring:
"he"
Not matching
Extract substring: "el"
Not matching
Extract substring: "ll" Match found
Final Result: 2
Optimized Code
Complexity Analysis
Time Complexity: O(n * m)Explanation:
Substring comparison is performed for every window.
Space Complexity: O(m) Explanation:
Extra substring storage may be used.
Edge Cases