Challenge: Implement strStr()

Welcome to Day 7 of our 100 Days DSA Challenge! 🚀 Today’s challenge involves the implementation of strStr(), a classic problem in string manipulation. Let’s unravel the mysteries of finding the first occurrence of a substring within a given string.

The Challenge:

Implement the strStr() function, which returns the index of the first occurrence of the needle in the haystack, or -1 if the needle is not part of the haystack.

Clarification:

  • When the needle is an empty string, the function should return 0.

Example:

const haystack = "hello";
const needle = "ll";
// Output: 2 (index of the first occurrence of "ll" in "hello")

Challenge Yourself:

Before exploring the solution, challenge yourself to think about how you would approach this problem. Can you optimize the code further?

The Solution:

const strStr = (haystack, needle) => {
    if (!needle) {
        return 0;
    }

    let needleLength = needle.length;
    for (let i = 0; i < haystack.length; i++) {
        let str = haystack.substr(i, needleLength);
        if (needle == str) {
            return i;
        }
    }

    return -1;
}

Solution Logic:

  1. Handle Empty Needle:
    • If the needle is an empty string, return 0.
  2. Iterate Through the Haystack:
    • Use a for loop to iterate through each character in the haystack.
  3. Extract Substrings:
    • Extract substrings from the haystack using substr() starting from the current index and having a length equal to the length of the needle.
  4. Check for Match:
    • Compare the extracted substring with the needle. If they match, return the current index.
  5. Return -1 if No Match:
    • If the loop completes without finding a match, return -1.

Conclusion:

Congratulations on completing Day 7 of our DSA Challenge! Manipulating substrings is a crucial skill in coding, and mastering it enhances your algorithmic abilities. Stay tuned for tomorrow’s challenge, and keep the coding spirit alive!

Happy coding! 🌟💻

#100DaysDSAChallenge #DataStructures #Algorithms #ProgrammingCommunity #CodeNewbie

Leave a Reply

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