Algo-Sim › String Algorithms
Find the Index of the First Occurrence (KMP)
Medium · String Algorithms · step through it in Java, Python and C++ on your own input
Pattern search in O(n + m): precompute each prefix’s longest border (lps), then scan the text once, sliding the pattern by its border on a mismatch instead of moving back.
Problem
Given a text haystack and a pattern needle, return the index where needle first occurs in haystack, or -1 if it never does. This version uses Knuth-Morris-Pratt so the text is scanned once, never backing up.
Constraints
- 1 ≤ haystack.length, needle.length ≤ 10⁴
- Both strings contain only lowercase English letters
- The naive scan is O(n·m) in the worst case; KMP is O(n + m)
Edge cases to test
- Empty pattern: match at 0
- Pattern longer than the text
- Overlapping matches:
"aaaa", pattern"aa"
Follow-up questions
- Why is KMP O(n + m)?
- The text pointer never moves back, and each fallback through lps shortens the match, so total fallbacks are bounded by forward steps.
- When would you use something else?
- Z-function for the same jobs with simpler code, Rabin–Karp for many patterns of one length, Aho–Corasick for many patterns at once.
Solution
Java
public int strStr(String haystack, String p) {
int m = p.length();
int[] lps = new int[m];
for (int i = 1, len = 0; i < m; ) {
if (p.charAt(i) == p.charAt(len)) lps[i++] = ++len;
else if (len > 0) len = lps[len - 1];
else lps[i++] = 0;
}
for (int i = 0, j = 0; i < haystack.length(); ) {
if (haystack.charAt(i) == p.charAt(j)) {
i++;
j++;
if (j == m) return i - m;
} else if (j > 0) j = lps[j - 1];
else i++;
}
return -1;
}Python
def str_str(haystack, p):
m = len(p)
lps = [0] * m
i, length = 1, 0
while i < m:
if p[i] == p[length]:
length += 1
lps[i] = length
i += 1
elif length > 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
i = j = 0
while i < len(haystack):
if haystack[i] == p[j]:
i += 1
j += 1
if j == m:
return i - m
elif j > 0:
j = lps[j - 1]
else:
i += 1
return -1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int strStr(string &haystack, string &p) {
int m = int(p.size());
vector<int> lps = vector<int>(m);
for (int i = 1, len = 0; i < m;) {
if (p[i] == p[len])
lps[i++] = ++len;
else if (len > 0)
len = lps[len - 1];
else
lps[i++] = 0;
}
for (int i = 0, j = 0; i < int(haystack.size());) {
if (haystack[i] == p[j]) {
i++;
j++;
if (j == m)
return i - m;
} else if (j > 0)
j = lps[j - 1];
else
i++;
}
return -1;
}
};