Skip to problem
←

First Occurrence in a String

Easy 0 attempts

You're given two strings, haystack and needle. Locate the first position in haystack where needle appears as a contiguous substring and return that index; if needle never occurs in haystack, return -1.

Function contract

haystack and needle are nonempty strings of lowercase English letters.

Output: Return the zero-based starting index of the first contiguous occurrence of needle in haystack, or -1 if absent.

Example 1

Input
haystack = "sadbutsad"
needle = "sad"
Output
0

Example 2

Input
haystack = "leetcode"
needle = "leeto"
Output
-1
Constraints
  • 1 <= haystack.length, needle.length <= 10^4
  • haystack and needle consist of lowercase English letters

Knuth–Morris–Pratt Search

Build lps[i], the length of the longest proper prefix of needle[0..i] that is also a suffix. On a mismatch, this table tells us how much of the current match can be reused without moving backward through haystack.

Return as soon as the complete pattern matches; this is its first occurrence.

javascript
function strStr(haystack, needle) {
  const lps = Array(needle.length).fill(0);
  for (let i = 1, matched = 0; i < needle.length;) {
    if (needle[i] === needle[matched]) {
      lps[i++] = ++matched;
    } else if (matched > 0) {
      matched = lps[matched - 1];
    } else {
      i++;
    }
  }

  for (let i = 0, matched = 0; i < haystack.length;) {
    if (haystack[i] === needle[matched]) {
      i++;
      matched++;
      if (matched === needle.length) return i - matched;
    } else if (matched > 0) {
      matched = lps[matched - 1];
    } else {
      i++;
    }
  }
  return -1;
}

Time: O(n + m) | Space: O(m), where n and m are the haystack and needle lengths.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript