#28

Find the Index of the First Occurrence in a String

Easy KMP

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the index where needle first appears in haystack, or -1 if it doesn't appear.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: where does needle first appear in haystack?

Why this works: KMP's LPS table remembers how much of the needle still matches after a mismatch, so the haystack pointer never goes back.

Example: needle "abab" → lps [0, 0, 1, 2]

text "abaabab": match "aba", mismatch at 'a' vs 'b'jump j to lps[2] = 1 (keep "a") instead of restartingcontinue → match found at index 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Resetting j to 0 on every mismatch — that's the brute force, and it misses overlapping matches like "aab" in "aaab".

Solve on LeetCode ↗
Complexity
  • Time: O(n + m).
  • Space: O(m).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon