Skip to content
Problem 28 · LeetCode 28(opens in a new tab)

Find the Index of the First Occurrence in a String

EasyStrings

You are given two strings, haystack and needle. Find the first place where needle appears inside haystack as a contiguous run of letters.

Return the index in haystack where that first copy begins. If needle never appears, return -1.

Example 1

Input:  haystack = "catcatcher", needle = "catch"
Output: 3
Why:    "catc" at index 0 breaks on the fifth letter; "catch" starts at 3
2 more examples and the constraints

Example 2

Input:  haystack = "pepper", needle = "pip"
Output: -1
Why:    there is no i in "pepper"

Example 3

Input:  haystack = "aaa", needle = "aaaa"
Output: -1
Why:    the needle is longer than the haystack

Constraints

  • 1 ≤ length of haystack ≤ 10,000
  • 1 ≤ length of needle ≤ 10,000
  • Both strings use only lowercase English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every startO(n·m)
  2. Knuth–Morris–Pratt (KMP)O(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work, 10,000 letters, worst caseVerdict
Try every startO(n·m)
Passes here; slow on repetitive text
Knuth–Morris–Pratt (KMP)O(n + m)
Best; each letter read a bounded number of times

n = length of haystack, m = length of needle.

Edge cases to test

  • Needle longer than haystack. "aaa" and "aaaa" give -1; the brute force loop simply never runs.
  • Equal strings. "abc" in "abc" gives 0.
  • Match at the very end. "xyz" in "wxyz" gives 1; the last start is n − m, inclusive.
  • Overlapping copies. "aa" in "aaaa" gives 0, the first copy, not the last.
  • Repetitive text. Many a's followed by a b is the worst case for the brute force.

Common mistakes

  • Stopping the start loop at n − m − 1 and missing a match that ends on the last letter.
  • In KMP, moving i back after a mismatch, which turns it back into the brute force.
  • Using lps[j] instead of lps[j − 1] when falling back.

How to talk through it

  1. 1Clarify. Can the needle be longer than the haystack? Do we want the first copy if there are several?
  2. 2Give the brute force. Try every start; say it is O(n·m) and show the repetitive input that hurts.
  3. 3Name what is wasted. A failed try already read letters that are a prefix of the needle.
  4. 4Code KMP. Build the border table, then scan once without moving i back.
  5. 5Test out loud. Run a match at the end, a missing needle, and overlapping copies.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?