Find the Index of the First Occurrence in a String Leetcode Solution

Index Of the first Occurrence Leetcode Problem :

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.


Index Of First Occurrence Leetcode Solution :

Constraints :

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

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.

In the “3 sum” problem you are given an integer array nums, the goal is to find all  unique triplets within the array such that the sum of the elements in each triplet is equal to zero (i.e.,nums[i] + nums[j] + nums[k] == 0), and the indices i, j, and k are all distinct (i.e., i != j, i != k, and j != k). 

Here are the key points for the given constraints and examples:

  • Constraints:

    • The length of the nums array is between 3 and 3000.
    • The values in the nums array can range from -100,000 to 100,000.

Approach :

Two Pointer approach:

  • Initialize 2 pointers i and j, store starting index of i in ind.
  • While haystack[i] and needle[j] are equal increament the i and j both pointer.
  • if j has traversed all the needle string, so return the starting index of i, where you started.
  • else again intialize j with 0, to traverse the string needle again.
  • Update the i pointer with ind + 1.
  • Repeat the steps from 2, if didn’t get the ans in previous step.
  • return -1, after checking all the possibilities, out of the loop.
  • End.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :