LeetCode problem #28 — StrStr (JavaScript)

Duncan McArdle
1 min readDec 18, 2020

--

In this LeetCode challenge, we’re asked to write a function similar to C++’s StrStr. By way of a quick refresher, StrStr is a function that takes two strings; string A (the haystack) and string B (the needle), and returns whether (and where) you can find string B in string A (the needle in the haystack).

In other words, if provided with a haystack of hello , and a needle of lo , StrStr would return 3, as that is where the needle appears in the haystack. According to the LeetCode spec, if we cannot find the needle in the haystack, we should return -1, and if the needle is empty, we should return 0.

Obviously there are a variety of functions in JavaScript to achieve this, but that’s not really in the spirit of LeetCode, so let’s look at making a solution.

Solution 1: Loop

This solution loops through the haystack until it finds the start of the needle, and then checks if the letters that follow in the haystack match that of the needle. If a full match is detected, then this position is returned, otherwise the traversal of the haystack continues. If we reach the end of the haystack without finding the needle (or more accurately, if we traverse far enough into the haystack that the needle cannot be found), we return -1.

--

--

Duncan McArdle
Duncan McArdle

Written by Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.

No responses yet