
Problem
Solution
Submissions
String matching
Certification: Basic Level
Accuracy: 50%
Submissions: 2
Points: 5
Write a Java program to implement the strStr() function, which finds the first occurrence of a substring (needle) in a string (haystack). Return the index of the first occurrence of the needle in the haystack, or -1 if the needle is not part of the haystack.
Example 1
- Input: haystack = "hello", needle = "ll"
- Output: 2
- Explanation:
- Step 1: We need to find the first occurrence of "ll" in "hello".
- Step 2: Iterate through the haystack string, comparing substrings of length needle.length with the needle.
- Step 3: At index 0, substring "he" doesn't match "ll".
- Step 4: At index 1, substring "el" doesn't match "ll".
- Step 5: At index 2, substring "ll" matches the needle "ll".
- Step 6: Return index 2 as the first occurrence.
Example 2
- Input: haystack = "aaaaa", needle = "bba"
- Output: -1
- Explanation:
- Step 1: We need to find the first occurrence of "bba" in "aaaaa".
- Step 2: Iterate through the haystack string, comparing substrings of length needle.length with the needle.
- Step 3: Check substrings at indices 0, 1, and 2, all of which are "aaa".
- Step 4: No substring matches "bba".
- Step 5: Return -1 since the needle is not found in the haystack.
Constraints
- 0 ≤ haystack.length, needle.length ≤ 5 * 10^4
- haystack and needle consist of only lowercase English characters
- Return 0 if needle is an empty string
- Time Complexity: O(n*m) where n is the length of haystack and m is the length of needle
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Consider edge cases: empty needle should return 0, and if needle is longer than haystack, return -1
- Use a sliding window approach to compare substrings of haystack with needle
- Start from each position in haystack and check if the substring matches the needle
- Optimize by breaking the comparison as soon as a mismatch is found
- Consider using the KMP (Knuth-Morris-Pratt) algorithm for a more efficient solution if needed