MediumPro challengePythonJavaScriptTypeScript
Strings — Find the Needle (KMP)
AlgorithmsStringsKMPPattern Matching
solve(haystack, needle) — return the index of the first occurrence of needle inhaystack, or -1 if it does not occur. An empty needle returns 0. Do not useindexOf / find / includes.
The naive double loop is O(n · m) on inputs like "aaaa…ab". Knuth–Morris–Pratt gets
O(n + m) by never moving backwards in the haystack. First build the failure tablelps[i]: the length of the longest proper prefix of needle[0..i] that is also a suffix of
it. Then scan the haystack; on a mismatch, instead of restarting, fall back tolps[matched - 1] and reuse what you already matched.
Examples
solve("sadbutsad", "sad") → 0
solve("leetcode", "leeto") → -1
solve("mississippi", "issip") → 4
solve("aabaaabaaac", "aabaaac") → 4Sample tests
Test #1Match at the start
Input: ["sadbutsad","sad"]
Output: 0
Test #2Not found
Input: ["leetcode","leeto"]
Output: -1
Test #3Partial matches restart
Input: ["mississippi","issip"]
Output: 4