The function has several drawbacks.

For starters it should be declared like

std::string::size_type strStr( const std::string &haystack, const std::string &needle );

and if the second string is not found in the first string the function should return std::string::npos as all similar member functions of the class std::string do.

The function parameters shell be of constant referenced types.

The condition in this if-statement

if (haystack.empty() && !needle.empty())

has a redundant operand. It could be rewritten like

if (haystack.empty())

This loop

for (i; i < haystack.length(); i++) 

should stop its iterations when the size of the tail of the first string is less than the size of the second string.

in this if-statement

if (haystack[i++] != needle[j]) {

the variable i is incremented that results in incrementing the variable two times: one in this statement and the second time in the loop.

The second pair of these statements

        if (j == needle.length()) {
        return ans;

is redundant.

The function can be written the following way as it is shown in the demonstrative program.

#include <iostream>
#include <string>

std::string::size_type strStr( const std::string &haystack, const std::string &needle )
{
    if ( needle.empty() )
    {
        return 0;
    }
    else if ( haystack.empty() )
    {
        return -std::string::npos;
    }
    else
    {
        std::string::size_type ans = std::string::npos;

        auto n1 = haystack.length();
        auto n2 = needle.length();

        for ( std::string::size_type i = 0; ans == std::string::npos && i + n2 <= n1; i++ )
        {
            std::string::size_type j = 0;
            while ( j < n2 && haystack[i+j] == needle[j] ) j++;

            if ( j == n2 ) ans = i;
        }

        return ans;
    }
}

int main() 
{
    std::string haystack( "mississippi" );
    std::string needle( "issip" );

    std::cout << strStr( haystack, needle ) << '\n';

    return 0;
}

Its output is

4

Answer from Vlad from Moscow on Stack Overflow
🌐
LeetCode
leetcode.com › problems › find-the-index-of-the-first-occurrence-in-a-string
Find the Index of the First Occurrence in a String - LeetCode
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.
Top answer
1 of 2
3

The function has several drawbacks.

For starters it should be declared like

std::string::size_type strStr( const std::string &haystack, const std::string &needle );

and if the second string is not found in the first string the function should return std::string::npos as all similar member functions of the class std::string do.

The function parameters shell be of constant referenced types.

The condition in this if-statement

if (haystack.empty() && !needle.empty())

has a redundant operand. It could be rewritten like

if (haystack.empty())

This loop

for (i; i < haystack.length(); i++) 

should stop its iterations when the size of the tail of the first string is less than the size of the second string.

in this if-statement

if (haystack[i++] != needle[j]) {

the variable i is incremented that results in incrementing the variable two times: one in this statement and the second time in the loop.

The second pair of these statements

        if (j == needle.length()) {
        return ans;

is redundant.

The function can be written the following way as it is shown in the demonstrative program.

#include <iostream>
#include <string>

std::string::size_type strStr( const std::string &haystack, const std::string &needle )
{
    if ( needle.empty() )
    {
        return 0;
    }
    else if ( haystack.empty() )
    {
        return -std::string::npos;
    }
    else
    {
        std::string::size_type ans = std::string::npos;

        auto n1 = haystack.length();
        auto n2 = needle.length();

        for ( std::string::size_type i = 0; ans == std::string::npos && i + n2 <= n1; i++ )
        {
            std::string::size_type j = 0;
            while ( j < n2 && haystack[i+j] == needle[j] ) j++;

            if ( j == n2 ) ans = i;
        }

        return ans;
    }
}

int main() 
{
    std::string haystack( "mississippi" );
    std::string needle( "issip" );

    std::cout << strStr( haystack, needle ) << '\n';

    return 0;
}

Its output is

4

2 of 2
2

The problem is that you modify i in

if (haystack[i++] != needle[j]) {

Thus preventing a second potential match from being explored. Try

if (haystack[i + j] != needle[j]) {

and fix any knock-on issues. I expect it to work as-is, though.

Discussions

programming challenge - LeetCode:implement strstr C# - Code Review Stack Exchange
🌐 codereview.stackexchange.com
June 28, 2019
debugging - Leetcode 28. Implement strStr() -- Why my code failed? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
LeetCode #28 - Implement StrStr (Easy)
Are those substring functions + comparison to needle O(1)? More on reddit.com
🌐 r/leetcode
1
3
February 26, 2020
Is it okay to write a one-liner on an interview?

An interviewer is trying to assess your problem solving and programing know how. Do you think this approach exhibits that?

More on reddit.com
🌐 r/leetcode
15
31
May 9, 2021
🌐
Medium
medium.com › @kajohnson3140 › implement-strstr-javascript-leetcode-a40258a59ef3
Implement strStr(), JavaScript, LeetCode | by K. Johnson | Medium
October 22, 2021 - In this article I’m going to go over the Implement strStr() from the String section of LeetCode’s Top interview Questions (Easy…
🌐
Codeewander
codeewander.github.io › leetcode 28 - implement strstr()
LeetCode 28 - Implement strStr() | Kira Yang
/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function (haystack, needle) { const len = needle.length; if (len === 0) return 0; for (let i = 0; i < haystack.length; i++) { if (haystack.substring(i, i + len) === needle) { return i; } } return -1; };
🌐
Red Quark
redquark.org › leetcode › 0028-implement-strstr
LeetCode #28 - Implement StrStr | Red Quark
December 14, 2020 - public class ImplementStrStr { public int strStr(String haystack, String needle) { // Base condition if (haystack == null || needle == null) { return -1; } // Special case if (haystack.equals(needle)) { return 0; } // length of the needle int needleLength = needle.length(); // Loop through the haystack and slide the window for (int i = 0; i < haystack.length() - needleLength + 1; i++) { // Check if the substring equals to the needle if (haystack.substring(i, i + needleLength).equals(needle)) { return i; } } return -1; } }
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72795129 › leetcode-28-implement-strstr-why-my-code-failed
debugging - Leetcode 28. Implement strStr() -- Why my code failed? - Stack Overflow
class Solution { public int strStr(String haystack, String needle) { if (needle.length() == 0) { return 0; } String result = ""; int i = 0; int j = 0; while (i < haystack.length() && j < needle.length()) { if (haystack.charAt(i) == needle.charAt(j)) { result += needle.charAt(j); i++; j++; } else { result = ""; i++; } } if (result.equals(needle)) { return i - needle.length(); } return -1; }
🌐
DEV Community
dev.to › rohan2596 › leetcode-implement-strstr-with-solution-474a
LeetCode :-Implement strStr() with Solution - DEV Community
June 2, 2022 - class Solution { public int strStr(String haystack, String needle) { return haystack.indexOf(needle); } } In this article, we learned way to solve LeetCode Problem Implement strStr() using java.
🌐
DevGenius
blog.devgenius.io › leetcode-28-implement-strstr-solution-with-images-7066d68c2262
LeetCode: 28. Implement strStr() (Solution with images) | by Alex Murphy | Dev Genius
August 2, 2022 - Link: → https://leetcode.com/problems/implement-strstr/ Implement strStr(). 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.
🌐
Gitbooks
macctown.gitbooks.io › leetcode-solutions-camp-java- › content › implement_strstr.html
Implement strStr() · Leetcode Solutions Camp(Java)
public class Solution { public int strStr(String haystack, String needle) { if(needle.length()==0){ return 0; } if(haystack.length()==0){ return -1; } if(haystack.length()<needle.length()){ return -1; } int s_count = 0; /*haystack pointer*/ int n_count = 0; /*needle pointer*/ while( s_count < haystack.length() ){ if(haystack.charAt(s_count) == needle.charAt(n_count)){ n_count++; if(n_count == needle.length()){ return s_count-n_count+1; } } else{ s_count = s_count - n_count; n_count=0; } s_count++; } return -1; } }
🌐
Cody Bonney
codybonney.com › leetcode-implement-strstr-solution-using-typescript
Implement strStr() solution using TypeScript
July 26, 2020 - /** * Implement strStr() * Return the index of the first occurrence of needle * in haystack, or -1 if needle is not part of haystack.
🌐
GitHub
github.com › mohandsakr › My-solutions-on-leetcode.com › blob › master › 28. Implement strStr().cpp
My-solutions-on-leetcode.com/28. Implement strStr().cpp at master · mohandsakr/My-solutions-on-leetcode.com
problem link:https://leetcode.com/problems/implement-strstr/ problem name:28. Implement strStr(). status:accpted · author :mohand sakr · · · · · */ · · · · class Solution { public: int strStr(string haystack, string needle) { ·
Author   mohandsakr
🌐
LeetCode
leetcode.com › discuss › post › 1688903 › solved-all-two-pointers-problems-in-100-z56cn
Solved all two pointers problems in 100 days. - Discuss - LeetCode
January 13, 2022 - SubString (*) https://leetcode.com/problems/implement-strstr/ https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ https://leetcode.com/problems/long-pressed-name/ https://leetcode.com/problems/longest-uncommon-subsequence-ii/ https://leetcode.com/problems/compare-version-numbers/ https://leetcode.com/problems/camelcase-matching/ https://leetcode.com/problems/expressive-words/
🌐
Rishabh1403
rishabh1403.com › posts › coding › leetcode › 2020 › 03 › leetcode-implement-strstr
Leetcode | Solution of implement strStr() in JavaScript | Rishabh Jain
In any case, let's see a simple implementation of the above logic. var strStr = function (haystack, needle) { if (needle.length === 0) return 0; if (needle === haystack) return 0; for (let i = 0; i <= haystack.length - needle.length; i++) { ...
🌐
Coderscat
coderscat.com › leetcode-implement-strstr
LeetCode: Implement strStr() - Coder's Cat
coderscat.com · 2025 Copyright | All Rights Reserved. Privacy Policy