LeetSolved

Find solutions to all LeetCode problems here.

28.

Find the Index of the First Occurrence in a String

Easy

Problem Description

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.

Examples

Input: hello, ll
Output: 2

Input: aaaaa, bba
Output: -1

Input: mississippi,issip
Output: 4

Constraints

Approach to Solve

Use a sliding window approach to check for the first occurrence of needle in haystack.

Code Implementation

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0
        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1

Explanation

This solution uses a sliding window approach to check for the first occurrence of needle in haystack. Here's a detailed explanation of the algorithm:

  1. Check if needle is empty: If the needle is empty, return 0.

  2. Iterate through the haystack: Use a loop to iterate through the haystack from the start to the position where the last character of the needle would fit.

  3. Compare substrings: For each position in the haystack, extract a substring of the same length as the needle and compare it with the needle.

  4. Return the index: If a match is found, return the current index. If no match is found after the loop, return -1.

This approach ensures that the entire haystack is scanned, and the first occurrence of the needle is found if it exists.

Time Complexity: O(n * m), where n is the length of the haystack and m is the length of the needle. In the worst case, the algorithm may need to compare every substring of length m in the haystack. Space Complexity: O(1), as we only use a constant amount of extra space for the loop index and substring extraction.

Complexity

  • Time Complexity: O(n * m)
  • Space Complexity: O(1)
Code copied to clipboard!