
Problem
Solution
Submissions
First Occurrence of Substring
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to implement the strStr()
function. Given two strings haystack
and needle
, return the index of the first occurrence of needle
in haystack
, or -1 if needle
is not part of haystack
.
Note: For the purpose of this problem, when needle
is an empty string, the function should return 0. This is consistent with C's strstr()
and Java's indexOf()
.
Example 1
- Input: haystack = "hello", needle = "ll"
- Output: 2
- Explanation:
Step 1: Compare "he" with "ll". No match.
Step 2: Compare "el" with "ll". No match.
Step 3: Compare "ll" with "ll". Match found.
Step 4: The starting index of the match is 2.
Example 2
- Input: haystack = "aaaaa", needle = "bba"
- Output: -1
- Explanation:
Step 1: Compare "aaa" with "bba". No match.
Step 2: Compare "aaa" with "bba". No match.
Step 3: Compare "aa" with "bba". No match.
Step 4: No match found in the entire haystack.
Step 5: Return -1.
Constraints
- 0 ≤ haystack.length, needle.length ≤ 5 * 10^4
- haystack and needle consist of only lowercase English characters
- Time Complexity: O(n * m) for the naive approach, where n is the length of haystack and m is the length of needle
- Space Complexity: O(1), constant extra space
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
- Use the naive approach: check for the needle at each position of the haystack
- Implement a more efficient algorithm like Knuth-Morris-Pratt (KMP) or Boyer-Moore
- Use a sliding window approach to iterate through the haystack
- For each position in the haystack, check if the substring starting at that position matches the needle
- Take advantage of early termination when a mismatch is found