8.Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Pattern Searching

Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1

Solution I: (Bruteforce)

class Solution
{
public:
    int strStr(string haystack, string needle)
    {

        int ndl_len = needle.length();

        if (ndl_len == 0)
        {
            return 0;
        }
        else if (haystack.length() == 0 || ndl_len > haystack.length())
        {
            return -1;
        }

        char first_char = needle[0];
        int pos = -1;
        for (int i = 0; i <= haystack.length() - ndl_len; i++)
        {

            if (haystack[i] == first_char)
            {
                string sub = haystack.substr(i, ndl_len);
                if (sub == needle)
                {
                    pos = i;
                    break;
                }
            }
        }

        return pos;
    }
};

Time Complexity: O(n * m)

Solution II (Using KMP Algo):

Time Complexity: O(n + m)

Solution III : (Rabin Krap Algo)

Time Complexity: O(n + m)

Last updated

Was this helpful?