‹ DS&A interview · Socratic
DSA · Strings · #75

Find the Index of the First Occurrence in a String

Module 62 · difficulty 2/5·⏱ 30:00starts on first keystroke

Given two strings `haystack` and `needle`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`. Implement the function `strStr(haystack, needle)` that returns this index.

Examples
  • haystack = "sadbutsad", needle = "sad" → 0 — "sad" occurs at index 0 and 6; the first occurrence is index 0.
  • haystack = "leetcode", needle = "leeto" → -1 — "leeto" does not occur in "leetcode", so return -1.
  • haystack = "abc", needle = "" → 0 — An empty needle matches at index 0 by convention.
Constraints
  • · 1 <= haystack.length, needle.length <= 10^4 (needle may also be empty for this variant)
  • · haystack and needle consist of only lowercase English characters.
  • · Return 0 when needle is the empty string.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.