# Find The Index Of The First Occurrence In A String Program Solution

Problem Statement

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`.

We at gradjobopenings.com provide free job alerts of freshers job drives. In this website we list on campus job openings for freshers and off campus job openings for freshers and also work from home job openings. This is the best website to apply for off campus drive in India. Visit our website for government job alerts and private job alerts. We also list free interview notes and study materials, one of the best interview study website.comfortable to face the interviews:

Example 1:

```Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
```

Example 2:

```Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
```

Constraints:

• `1 <= haystack.length, needle.length <= 104`
• `haystack` and `needle` consist of only lowercase English characters.
• Time: O((m – n)n)O((mn)n), where m = |\texttt{haystack}|m=∣haystack∣ and n = |\texttt{needle}|n=∣needle∣
• Space: O(1)O(1)

### Find The Index Of The First Occurrence In A String Program Solution in C++

``````class Solution {
public:
int strStr(string haystack, string needle) {
const int m = haystack.length();
const int n = needle.length();

for (int i = 0; i < m - n + 1; i++)
if (haystack.substr(i, n) == needle)
return i;

return -1;
}
};
``````

### Find The Index Of The First Occurrence In A String Program Solution in JAVA

``````class Solution {
public int strStr(String haystack, String needle) {
final int m = haystack.length();
final int n = needle.length();

for (int i = 0; i < m - n + 1; ++i)
if (haystack.substring(i, i + n).equals(needle))
return i;

return -1;
}
}
``````

### Find The Index Of The First Occurrence In A String Program Solution in Python

``````class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)

for i in range(m - n + 1):
if haystack[i:i + n] == needle:
return i

return -1
``````
error: Content is protected !!