first occurrence of needle in haystack (Implement strStr())

Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

The naive way is just to iterate through every character in haystack and compare every single character in the substring of haystack with needle. A more efficient way uses the fact that after the (M+N-1)th character in haystack (Assume haystack has M characters and needle has N), we have substrings with length less than N. Then needle cannot occur in any of those substrings so we do not need to look at them.

Code (Java):

public class Solution {
    public String strStr(String haystack, String needle) {
        if(needle.length() == 0)  
            return haystack;
        if(haystack.length() < needle.length())
            return null;
        int diff = haystack.length() - needle.length() + 1;
        for(int i = 0; i < diff; ++i) {
                return haystack.substring(i);
        return null;

Code (C++):

class Solution {
    char *strStr(char *haystack, char *needle) {
            return haystack;
        char *p1Adv = haystack;
        char *p2 = needle;
        while(*++p2) {
        char* p1Begin = haystack;
        while(*p1Adv) {
            char* p1 = p1Begin;
            char* p2 = needle;
            while(*p1 && *p2 && *p1 == *p2) {
                return p1Begin;
        return NULL;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: