Find the Index of the First Occurrence in a String (LeetCode 28): Interview Notes
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.
Approach
Slide a window of length m = needle.length across haystack. For each start i from 0 to n-m, compare the substring (or character-by-character). Return the first match; if none, return -1. Mention KMP/Z-algorithm as a follow-up for better worst-case. Dry-run on haystack sadbutsad, needle sad.
Complexity
Naive: time O((n-m+1)*m), space O(1). KMP: time O(n+m), space O(m).
Practice tip
Keep the same narration under time pressure with real-time interview help.
Disclosure: I work on Linkjob AI.