Find The Index Of The First Occurrence In A String

Solution For Find The Index Of The First Occurrence In A String

Problem Statement:

Given two strings, haystack and needle, return the index of the first occurrence of needle in haystack. If needle is not part of haystack, return -1.

Example:

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

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

Solution:

The problem can be solved using the brute-force approach where we iterate through haystack and compare the substring of the same length as the needle to the needle. When we find a match we return the starting index of the match. If we don’t find any match, we return -1.

Algorithm:

  1. Check the base cases. If the needle is empty return 0. If the length of the haystack is less than the length of needle, return -1.

  2. Iterate through the haystack with a loop until haystack length minus needle length. For each iteration, take a substring of the same length as the needle and compare it to needle.

  3. If the current substring matches the needle, return the starting index of the match.

  4. If we do not find any match, return -1.

Time Complexity: O(n^2) [n is the length of the haystack]

Code:

class Solution:
def strStr(self, haystack: str, needle: str) -> int:

    if not needle:
        return 0

    h_len = len(haystack)
    n_len = len(needle)

    if h_len < n_len:
        return -1

    for i in range(h_len - n_len + 1):
        if haystack[i:i + n_len] == needle:
            return i

    return -1

Conclusion:

The problem can be solved using the brute-force approach where we iterate through haystack and compare the substring of the same length as the needle to the needle. When we find a match we return the starting index of the match. If we don’t find any match, we return -1.

Step by Step Implementation For Find The Index Of The First Occurrence In A String

public int findFirstOccurrence(String s, String target) {
    // edge case
    if (s == null || target == null || target.length() == 0) {
        return -1;
    }
    
    // use two pointers, one for s and one for target
    int i = 0, j = 0;
    
    // keep going until we reach the end of s
    while (i < s.length()) {
        // if the characters match, keep going
        if (s.charAt(i) == target.charAt(j)) {
            i++;
            j++;
        } 
        // otherwise, reset j back to 0 and move i back to where it was before we started matching
        else {
            i = i - j + 1;
            j = 0;
        }
        
        // if we reach the end of target, that means we found a match
        if (j == target.length()) {
            return i - j;
        }
    }
    
    // if we reach the end of s without finding a match, return -1
    return -1;
}
def findFirstOccurrence(string, target): 

# Initialize left and right pointers 
left = 0
right = len(string) - 1

# While left <= right, keep searching 
while left <= right: 

# Calculate the middle index 
mid = left + (right - left) // 2

# If the target is found at the middle 
if string[mid] == target: 

# Check if the target is the first occurrence by 
# comparing it to the element to its left 
if mid == 0 or string[mid - 1] != target: 
return mid 

# If the target is not the first occurrence, 
# search its left side 
else: 
right = mid - 1

# If the target is smaller than the middle element, 
# search its left side 
elif target < string[mid]: 
right = mid - 1

# If the target is greater than the middle element, 
# search its right side 
else: 
left = mid + 1

# If the target is not found in the array 
return -1
var findTheIndexOfTheFirstOccurrenceInAString = function(str, target) {
  // your code here
};
int findFirstOccurrence(string s, string target) {
    int targetLen = target.size(); 
    int sLen = s.size(); 
    
    // if target is empty, we can return 0 
    if (targetLen == 0) return 0; 
    
    // if s is empty, then obviously the target can't be found 
    if (sLen == 0) return -1; 
    
    // We can use a hashmap to keep track of all the characters in the target 
    unordered_map targetCharCount; 
    for (int i = 0; i < targetLen; i++) {
        targetCharCount[target[i]]++; 
    }
    
    // We can use a sliding window approach to keep track of the characters in the current window 
    int start = 0; 
    int end = 0; 
    int minWindowLen = INT_MAX; 
    int minWindowStart = 0; 
    int matched = 0; 
    
    // We can use a hashmap to keep track of all the characters in the current window 
    unordered_map currWindowCharCount; 
    
    // We keep expanding the window until we find a valid window 
    while (end < sLen) {
        // If the character at the current end index is not present in the target, we can keep expanding 
        if (targetCharCount.find(s[end]) == targetCharCount.end()) {
            end++; 
            continue;
        }
        
        // If the character at the current end index is present in the target, we add it to the current window 
        currWindowCharCount[s[end]]++; 
        
        // If the character at the current end index is present in the target and its frequency in the current window is less than or equal to its frequency in the target, we increment our matched variable 
        if (currWindowCharCount[s[end]] <= targetCharCount[s[end]]) {
            matched++; 
        }
        
        // If we have found a valid window, we try to shrink it from the start 
        while (matched == targetLen) {
            // If the current window size is less than the minimum window size, we update the minimum window size and the start index of the minimum window 
            if (end - start + 1 < minWindowLen) {
                minWindowLen = end - start + 1; 
                minWindowStart = start; 
            }
            
            // If the character at the start index is not present in the target, we can keep shrinking 
            if (targetCharCount.find(s[start]) == targetCharCount.end()) {
                start++; 
                continue; 
            }
            
            // If the character at the start index is present in the target, we remove it from the current window 
            currWindowCharCount[s[start]]--; 
            
            // If the character at the start index is present in the target and its frequency in the current window is less than its frequency in the target, we decrement our matched variable 
            if (currWindowCharCount[s[start]] < targetCharCount[s[start]]) {
                matched--; 
            }
            
            // We increment the start index to keep shrinking the window 
            start++; 
        }
        
        // We increment the end index to keep expanding the window 
        end++; 
    }
    
    // If we have not found a valid window, we return -1 
    if (minWindowLen == INT_MAX) return -1; 
    
    // Otherwise, we return the start index of the minimum window 
    return minWindowStart; 
}
public int FindIndex(string s, char c) { // return the index of the first occurrence of char c in string s int index = -1; for (int i = 0; i < s.Length; i++) { if (s[i] == c) { index = i; break; } } return index; }


Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]