InterviewPrepKit

Home / Coding / Arrays & Hashing

Find the Index of the First Occurrence in a String

easy Original ↗
Solving tips
  • Naive slide-and-compare over range(n - m + 1) is O(n*m) but passes at these bounds; the follow-up wants linear time.
  • KMP: precompute the prefix (lps) table so on mismatch after j matches you fall back to lps[j-1] without moving the haystack pointer backward, giving O(n+m).
  • Rabin-Karp alternative: a rolling hash makes each window compare O(1); always verify a hash hit with a real compare to avoid collision false positives.
  • Watch the last valid start (n - m) and the m > n guard; the KMP fallback is lps[j-1], not lps[j].

Problem

Given two strings haystack and needle, return the index of the first position in haystack where needle begins as a contiguous substring. If needle never occurs in haystack, return -1.

This is the classic strStr / substring-search problem: implement it yourself rather than calling a library find.

Examples

  • haystack = "sadbutsad", needle = "sad"0"sad" occurs at indices 0 and 6; the first is 0.
  • haystack = "leetcode", needle = "leeto"-1"leeto" never appears.
  • haystack = "mississippi", needle = "issip"4 — the match at index 1 fails at its 5th character, but index 4 succeeds.

Constraints

  • 1 <= len(haystack), len(needle) <= 10^4
  • Both strings consist of lowercase English letters only.

O(n·m) sliding comparison is accepted at these bounds, but the follow-up is the linear-time classics (KMP, Rabin–Karp).

Think about it first

Hint 1 How many starting positions in haystack could possibly begin a match, given the two lengths? What do you check at each one?
Hint 2 When a comparison fails several characters in, the naive method restarts from scratch one position later. What information about the characters you already matched is being thrown away?
Hint 3 Two classic fixes: give each window a rolling hash so a window compare is O(1) (Rabin–Karp), or precompute, for each prefix of the needle, the longest proper prefix that is also a suffix, so a mismatch can restart the needle pointer without moving the haystack pointer back (KMP).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.