Tutorialspoint
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
StringsAlgorithmsWalmartPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Handle the special case where the needle is an empty string, return 0.

 Step 2: Calculate the lengths of both the haystack and needle strings.
 Step 3: If the needle is longer than the haystack, return -1 as it cannot be a substring.
 Step 4: Iterate through the haystack up to the position (haystack length - needle length).
 Step 5: For each position, compare the substring starting at that position with the needle.
 Step 6: If all characters match, return the starting index of the match.
 Step 7: If no match is found after checking all possible positions, return -1.

Submitted Code :