Advertisement

Find the Index of the First Occurrence in a String - LeetCode 28 Solution

Find the Index of the First Occurrence in a String - Complete Solution Guide

Find the Index of the First Occurrence in a String is LeetCode problem 28, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 <= 10

Detailed Explanation

This problem, "Find the Index of the First Occurrence in a String," asks us to locate the starting position of a smaller string, `needle`, within a larger string, `haystack`. If `needle` appears multiple times, we're only interested in the very first one, meaning the one with the lowest starting index. If `needle` doesn't exist anywhere in `haystack`, our job is to return `-1`. The task is essentially a fundamental string search operation, a building block for many text processing functionalities.

Solution Approach

The provided solution employs a straightforward, brute-force 'sliding window' approach. It systematically checks every possible starting position in `haystack` where `needle` *could* begin. The algorithm iterates through `haystack` using an index `i`, which represents a potential starting point for `needle`. For each `i`, it extracts a substring from `haystack` that is exactly the same length as `needle`, specifically `haystack[i : i + len(needle)]`. It then directly compares this extracted substring with `needle` itself. If a match is found (`haystack[i : i + len(needle)] == needle`), the current index `i` is immediately returned because we are specifically looking for the *first* occurrence. If the loop completes without finding any match, it implies that `needle` is not present in `haystack`, and the function returns `-1`. The initial check for an empty `needle` is a critical edge case, adhering to the common convention that an empty string is considered to occur at index 0 of any string (even an empty one).

Step-by-Step Algorithm

  1. Step 1: Check for edge cases: If the needle is empty, return 0. If the needle is longer than the haystack, return -1.
  2. Step 2: Iterate through the haystack string using a loop. The loop runs from index 0 up to `len(haystack) - len(needle)`.
  3. Step 3: In each iteration, extract a substring from the haystack of the same length as the needle, starting at the current index `i`.
  4. Step 4: Compare the extracted substring with the needle. If they are equal, return the current index `i`.
  5. Step 5: If the loop completes without finding a match, return -1.

Key Insights

  • **Sliding Window Comparison:** The core idea is to simulate a 'window' of the `needle`'s length sliding across `haystack` from left to right. At each position `i`, we effectively create a temporary substring of `haystack` (from `i` to `i + len(needle) - 1`) and compare it against the entire `needle`. This systematic approach guarantees that the first possible match will be found.
  • **Precise Loop Bounds:** The loop iterating through `haystack` needs careful bounds. It runs from `i = 0` up to `len(haystack) - len(needle)`. This upper bound ensures that `i + len(needle)` never exceeds `len(haystack)`, preventing attempts to access characters beyond the string's end and ensuring that the extracted substring is always of the correct length to match `needle`.
  • **Leveraging Built-in Substring Operations (Python's Slicing):** Python's slicing syntax (`haystack[i:i + len(needle)]`) is a remarkably concise and often optimized way to extract a substring. This built-in language feature abstracts away the manual character-by-character comparison within the window, making the code exceptionally readable and less prone to off-by-one errors than a manual nested loop for comparison.

Complexity Analysis

Time Complexity: O(m*n)

Space Complexity: O(1)

Topics

This problem involves: Two Pointers, String, String Matching.

Companies

Asked at: Accenture, Adobe, Amazon, Apple, Bloomberg, Expedia, Google, IBM, IIT Bombay, Infosys, Meta, Microsoft, Pocket Gems, Uber, Warnermedia, Yahoo, Yandex, Zoho, tcs.