Implement function to find needle from a haystack. Interviewer was looking for coding skills.

Implement function to find needle from a haystack. Interviewer was looking for coding skills.

Ques:- Implement function to find needle from a haystack. Interviewer was looking for coding skills.
1 4929

One Answer on this Question

  1. #include
    using namespace std;

    int find(string needle, string haystack) {
    int i, j;
    for (i=0; i<haystack.size(); i++) { // i is my index for caterpillar
    for (j=0; j<needle.size(); j++) { // j is my index for pill
    if (i+j < haystack.size ()) {
    if (haystack[i+j] != needle[j]) {
    break;
    }
    }
    }
    return i;
    }
    return -1;
    }

    int main(){
    cout << find("pill", "caterpillar") << endl;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top