Taro Logo

Find the Index of the First Occurrence in a String

#5 Most AskedEasy
0 views
Topics:
StringsTwo Pointers

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.

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.

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the `needle` is an empty string?
  2. Are the `haystack` and `needle` strings case-sensitive?
  3. What character set do the strings consist of (e.g., standard ASCII, extended ASCII, or Unicode/UTF-8)?
  4. If the `needle` appears multiple times in the `haystack`, are we guaranteed to return the index of the very first occurrence?
  5. Can I use built-in language library functions and methods (like `indexOf` in JavaScript or `find` in Python), or should I implement the matching algorithm from scratch?

Brute Force Solution

Approach

Imagine you are searching for a specific short word inside a much longer piece of text by holding the short word against every possible spot in the text. The brute force strategy involves testing every single possible starting position in the text one by one to see if your short word matches the text starting at that exact spot.

Here's how the algorithm would work step-by-step:

  1. Place the start of your short word right at the very beginning of the long text.
  2. Compare the letters of your short word with the letters of the long text right beneath it, one letter at a time.
  3. If every single letter matches perfectly from start to finish, you have found your answer and you can stop right there.
  4. If even a single letter does not match, pick up your short word and shift it one single step to the right along the long text.
  5. Repeat the letter-by-letter comparison at this new position.
  6. Keep sliding the short word over by one step and checking for a complete match at every possible location until you either find a match or run out of text.
  7. If you check every possible starting spot and never find a complete match, conclude that the short word does not exist within the text at all.

Code Implementation

def find_first_occurrence(haystack_text, needle_word):
    # We limit the outer loop so we only check valid starting points where needle can fit
    for start_index in range(len(haystack_text) - len(needle_word) + 1):
        match_found = True
        
        # We iterate through each character of the needle to verify the current window match
        for needle_index in range(len(needle_word)):
            if haystack_text[start_index + needle_index] != needle_word[needle_index]:
                match_found = False
                break
        
        # If the inner loop finished without mismatches, we have found our exact starting index
        if match_found:
            return start_index

    # Returning negative one indicates the needle does not exist anywhere within the haystack
    return -1

Big(O) Analysis

Time Complexity
O(N * M) – Let N be the length of the long text and M be the length of the short word. The outer process tries every possible starting position in the long text, which happens roughly (N - M + 1) times. At each of these starting positions, the inner comparison checks up to M letters of the short word against the text. This leads to approximately N * M operations in the worst-case scenario, which simplifies to O(N * M).
Space Complexity
O(1) – The algorithm only uses a few primitive integer variables, such as loop counters and pointers, to track the current starting position and character matches. Because these variables occupy a fixed amount of memory regardless of the length of the text or the short word, no dynamic data structures or recursion stack frames are created. Therefore, the auxiliary space remains entirely constant as the input size grows.

Optimal Solution

Approach

Instead of checking every single possible starting point one by one, the smartest approach looks ahead and uses clever shortcuts to skip unnecessary checks. It sets up a helper guide based on the target pattern so that whenever a mismatch happens, the search process can jump forward immediately instead of starting over from scratch.

Here's how the algorithm would work step-by-step:

  1. Read through the main text and the target pattern to create a quick reference map that reveals repeating patterns within the target itself.
  2. Begin scanning through the main text from the very beginning while simultaneously comparing characters against the target pattern.
  3. Continue matching characters side by side as long as they are identical.
  4. If a mismatch happens after a partial match, use the reference map to shift your perspective forward immediately without losing the progress you can safely keep.
  5. Repeat this sliding comparison until you either successfully align the entire target pattern within the main text or run out of text to check.
  6. If the target pattern is successfully found, confirm its starting position as your final answer.

Code Implementation

class Solution:
    def strStr(self, main_text: str, target_pattern: str) -> int:
        if not target_pattern:
            return 0

        prefix_table = [0] * len(target_pattern)
        pattern_index = 0
        iterator_index = 1

        # Build the reference map to track repeating character patterns. 

        while iterator_index < len(target_pattern):
            if target_pattern[iterator_index] == target_pattern[pattern_index]:
                pattern_index += 1
                prefix_table[iterator_index] = pattern_index
                iterator_index += 1
            elif pattern_index > 0:
                pattern_index = prefix_table[pattern_index - 1]
            else:
                prefix_table[iterator_index] = 0
                iterator_index += 1

        text_index = 0
        pattern_index = 0

        # Scan the main text while matching characters against the pattern.

        while text_index < len(main_text):
            if main_text[text_index] == target_pattern[pattern_index]:
                text_index += 1
                pattern_index += 1

            if pattern_index == len(target_pattern):
                return text_index - pattern_index
            elif text_index < len(main_text) and main_text[text_index] != target_pattern[pattern_index]:
                # Shift perspective forward using the reference map instead of restarting.

                if pattern_index > 0:
                    pattern_index = prefix_table[pattern_index - 1]
                else:
                    text_index += 1

        return -1

Big(O) Analysis

Time Complexity
O(n + m) – The algorithm first processes the target pattern of length m to build the reference map, which takes linear time proportional to m. Next, it scans through the main text of length n at most once, using the reference map to shift the pattern forward and avoid redundant character comparisons upon a mismatch. The total operations scale linearly with the sum of the text and pattern lengths, approximating n + m steps in the worst case. Therefore, this efficient sliding comparison simplifies to a final time complexity of O(n + m).
Space Complexity
O(m) – The algorithm requires auxiliary space to build the quick reference map, which is an array of integers with a length equal to m, representing the length of the target pattern. As the target pattern size grows, the memory allocated for this prefix table scales proportionally with it, while the main text input does not contribute to the extra memory overhead.

Edge Cases

Needle is an empty string
How to Handle:
Return zero immediately as per standard convention where an empty string is found at index zero.
Haystack is shorter than needle
How to Handle:
Return a negative value immediately since a longer substring cannot exist inside a shorter string.
Needle and haystack are identical in length and content
How to Handle:
The loop will check the entire haystack and successfully return index zero.
Needle appears multiple times inside haystack
How to Handle:
Using a linear scan or standard search will naturally halt and return the starting index of the first occurrence.
Needle is not present in haystack
How to Handle:
The algorithm will exhaust all valid starting positions and return a negative value representing absence.
Haystack and needle contain all identical characters
How to Handle:
String comparison mechanics will correctly match the substring length and return the appropriate starting index.
Maximum sized strings approaching memory or time limits
How to Handle:
Implement an efficient string matching algorithm like KMP or optimized sliding window to prevent time limit exceedance.
Null or uninitialized input strings
How to Handle:
Check for null references at the beginning of the function and return a negative value to prevent runtime exceptions.
0/5 completed