Search⌘ K
AI Features

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

Explore how to apply the sliding window pattern to locate the first occurrence of a substring in a string. This lesson guides you through a step-by-step approach to implement an efficient solution with clear explanation of time and space complexity, helping you master substring search problems common in coding interviews.

Statement

Given two strings haystack and needle, return the index of the first occurrence of needle within haystack. If needle does not exist as a substring of haystack, return 1-1.

Constraints:

  • 11 \leq haystack.length, needle.length 104\leq 10^4

  • haystack and needle consist of only lowercase English characters

Solution

The key intuition behind this solution is to use a fixed-size sliding window of length equal to needle ...