Problem
Section titled “Problem”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.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"Output: 0Explanation: "sad" occurs at index 0 and 6.The first occurrence is at index 0, so we return 0.Example 2:
Input: haystack = "leetcode", needle = "leeto"Output: -1Explanation: "leeto" did not occur in "leetcode", so we return -1.Constraints:
-
haystack.length,needle.length haystackandneedleconsist of only lowercase English characters.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”The direct method tries every starting position and compares character by character. When a comparison fails after j matching characters, it shifts the needle by one and starts comparing from scratch, throwing away what it just learned — in the worst case (think haystack = "aaaa...ab", needle = "aaab").
Knuth–Morris–Pratt never re-reads a haystack character. After matching needle[0..j-1] we know exactly what the last j haystack characters are: they are needle[0..j-1]. If the next character mismatches, the next alignment that could still succeed is the one where a prefix of the needle lines up with a suffix of that matched part. Taking the longest such prefix loses no possible match.
That information depends only on the needle, so it is precomputed in lps (“longest proper prefix which is also a suffix”):
lps[i]= the length of the longest proper prefix ofneedle[0..i]that is also a suffix ofneedle[0..i].
For needle = "ababc", lps = [0, 0, 1, 2, 0]: in "abab" the prefix "ab" is also a suffix, so lps[3] = 2.
On a mismatch with j characters matched we set j = lps[j - 1] — “pretend we have matched only that many” — and compare the same haystack character again. The haystack index i only ever moves forward.
Algorithm
Section titled “Algorithm”- Build
lps. Keeplen, the length of the current prefix-suffix. For eachifrom1tom - 1:- while
len > 0andneedle[i] != needle[len], fall back withlen = lps[len - 1]; - if
needle[i] == needle[len], extend:len++; - set
lps[i] = len.
- while
- Search. Keep
j, the number of needle characters currently matched. For eachifrom0ton - 1:- while
j > 0andhaystack[i] != needle[j], fall back withj = lps[j - 1]; - if
haystack[i] == needle[j],j++; - if
j == m, the needle ends ati, so returni - m + 1.
- while
- Return
-1.
Building lps is the same procedure as the search, run with the needle against itself.
Walkthrough
Section titled “Walkthrough”The official examples never need a fall-back, so this trace uses haystack = "abababcab", needle = "ababc" (lps = [0,0,1,2,0]). Green cells matched, red is a mismatch, and the second row shows where the needle is aligned:
After the mismatch at i = 4, the matched "abab" ends with "ab", which is also how the needle starts, so the needle slides forward by two and keeps those two characters matched (j = lps[3] = 2) instead of starting over.
Complexity
Section titled “Complexity”- Time: . In the search loop
jgrows by at most one per haystack character, so it grows at most times in total; every fall-back makesjstrictly smaller, so there can be at most fall-backs overall. The same argument bounds buildinglpsby . - Space: — the
lpsarray.
Edge cases
Section titled “Edge cases”needlelonger thanhaystack:jcan never reachm, so the loop ends and-1is returned.- First occurrence: the function returns as soon as
j == m, so the earliest match wins (Example 1 returns0, not6). - Overlapping or repetitive patterns (
needle = "aaab"in"aaaaaab"): the fall-backs keep the useful overlap, which is exactly where the naive method degrades.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: int strStr(string haystack, string needle) { int n = haystack.size(), m = needle.size();
// lps[i]: longest proper prefix of needle[0..i] that is also a suffix of it. vector<int> lps(m, 0); for (int i = 1, len = 0; i < m; i++) { while (len > 0 && needle[i] != needle[len]) len = lps[len - 1]; if (needle[i] == needle[len]) len++; lps[i] = len; }
for (int i = 0, j = 0; i < n; i++) { while (j > 0 && haystack[i] != needle[j]) j = lps[j - 1]; if (haystack[i] == needle[j]) j++; if (j == m) return i - m + 1; } return -1; }};class Solution { public int strStr(String haystack, String needle) { int n = haystack.length(), m = needle.length();
// lps[i]: longest proper prefix of needle[0..i] that is also a suffix of it. int[] lps = new int[m]; for (int i = 1, len = 0; i < m; i++) { while (len > 0 && needle.charAt(i) != needle.charAt(len)) len = lps[len - 1]; if (needle.charAt(i) == needle.charAt(len)) len++; lps[i] = len; }
for (int i = 0, j = 0; i < n; i++) { while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = lps[j - 1]; if (haystack.charAt(i) == needle.charAt(j)) j++; if (j == m) return i - m + 1; } return -1; }}class Solution: def strStr(self, haystack: str, needle: str) -> int: m = len(needle)
# lps[i]: longest proper prefix of needle[0..i] that is also a suffix of it. lps = [0] * m length = 0 for i in range(1, m): while length > 0 and needle[i] != needle[length]: length = lps[length - 1] if needle[i] == needle[length]: length += 1 lps[i] = length
j = 0 for i, ch in enumerate(haystack): while j > 0 and ch != needle[j]: j = lps[j - 1] if ch == needle[j]: j += 1 if j == m: return i - m + 1 return -1Give it a try first
Attempt the problem on LeetCode — the code will still be here.






