Needle-Haystack
Find the First Occurrence of Needle in Haystack Problem Statement Implement a function strStr(haystack, needle) that returns the index of the first occurrence of needle in haystack , or -1 if needle is not part of haystack . Example : Input: haystack = "sadbutsad" , needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6 . The first occurrence is at 0 . Best Data Structure for Solving the Problem Since we're dealing with string pattern matching, a simple String traversal with two-pointer or substring comparison is efficient here. Multiple Approaches Approach 1: Built-in Method (Quick & Easy) Idea : Use Java's built-in indexOf() function. It's optimized under the hood and handles all edge cases. public int strStr (String haystack, String needle) { return haystack.indexOf(needle); } Approach 2: Manual Sliding Window (Interview-Ready) Idea : Slide a window of size needle.length() across haysta...