# 28 Implement strStr()

Implement strStr().

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

* The biggest part of the problem was identifing edge cases.
* O(N) time
* O(1) space

```cpp
int strStr(string haystack, string needle) {
    // are the same
    if (needle == haystack) return 0;
    // invalid cases
    else if (haystack.length() == 0 ||
        needle.length() > haystack.length()) return -1;
    // nothing can be anything, so return first index
    else if (needle.length() == 0) return 0;

    int length_n = needle.length();
    for (int i = 0; i < haystack.length() - length_n; i++) {
        if (haystack.substr(i, length_n) == needle) {
            return i;
        }
    }
    // check right edge case
    if (haystack.substr(haystack.length() - length_n, length_n) == needle)
        return haystack.length() - length_n;

    return -1;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/28_implement_strstr.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
