### Question

Implement strStr().

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

#### Clarification

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

#### Example 1:

Input: haystack = “hello”, needle = “ll”

Output: 2

#### Example 2:

Input: haystack = “aaaaa”, needle = “bba”

Output: -1

### Challenges

1. Check if the needle exists — when the needle is an empty string return 0.
2. Breakdown haystack into comparable parts
3. Find needle — to find a needle we will compare a part of a haystack with a needle
4. Return starting position of the needle.

### Let’s code

Check if the needle exists — when the needle is an empty string return 0. This is a pretty straightforward if statement.

`if (needle === "") {`
`     return 0;`
`}`

But if the needle exists we will proceed further.

#### Break down haystack into comparable parts

To break down the haystack into comparable parts, we need to determine the length of the needle, then we can use a slice() method to separate a part of the haystack.

We will create a variable for starting position and starting from that position will slice the haystack until we reach a position equal to starting position plus the length of the needle.

`let pos = 0;`
`haystack.slice(pos,pos+needle.length)`

#### Find needle — to find a needle we will compare a part of a haystack with a needle

Now we have comparable parts we will go through the haystack starting at the beginning. If the comparable part is equal to the needle, we will assign starting position to our result variable otherwise, we will move to the next slice. But what if we reached the end of the haystack? We will check if our position is less or equal to haystack size minus 1.

`if (pos<=haystack.length-1)`

If we’re still within the stack, we will use our recursive function find.

`function find(haystack, needle, pos) {`
`      if (haystack.slice(pos,pos+needle.length)===needle) {`
`            result = pos;`
`     } else {`
`           pos++;`
`           if (pos<=haystack.length-1) {`
`               find(haystack, needle, pos)`
`           }`
`      }`
`}`

#### Return starting position of the needle.

I’ve declared a variable result, which will be returned at the end of the function and unless we find the needle it will return -1.

Please check me out on the following social networks as well, I would love to hear from you! — LinkedIn, GitHub, and Facebook.

LeetCode Algorithm Challenge: Needle in a Haystack was originally published in JavaScript in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.