Arrays & Hashing · Pattern 21 of 26
KMP: string matching in O(n + m)
The prefix function lps[i] is the length of the longest proper prefix of the pattern that is also a suffix ending at i. On a mismatch, jump back to lps instead of restarting, so nothing is compared twice.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Find a pattern in a text in linear time
- Longest prefix that is also a suffix
- Repeated or periodic strings
The template
int strStr(String text, String pat) {
if (pat.isEmpty()) return 0;
int[] lps = new int[pat.length()]; // lps[i]: longest prefix = suffix of pat[0..i]
for (int i = 1, k = 0; i < pat.length(); i++) {
while (k > 0 && pat.charAt(i) != pat.charAt(k)) k = lps[k - 1];
if (pat.charAt(i) == pat.charAt(k)) k++;
lps[i] = k;
}
for (int i = 0, k = 0; i < text.length(); i++) {
while (k > 0 && text.charAt(i) != pat.charAt(k)) k = lps[k - 1]; // fall back, never restart
if (text.charAt(i) == pat.charAt(k)) k++;
if (k == pat.length()) return i - k + 1;
}
return -1;
} def str_str(text, pat):
if not pat:
return 0
lps = [0] * len(pat) # lps[i]: longest prefix = suffix of pat[:i+1]
k = 0
for i in range(1, len(pat)):
while k and pat[i] != pat[k]:
k = lps[k - 1]
if pat[i] == pat[k]:
k += 1
lps[i] = k
k = 0
for i, c in enumerate(text):
while k and c != pat[k]:
k = lps[k - 1] # fall back, never restart
if c == pat[k]:
k += 1
if k == len(pat):
return i - k + 1
return -1 int strStr(string text, string pat) {
if (pat.empty()) return 0;
vector<int> lps(pat.size(), 0); // lps[i]: longest prefix = suffix of pat[0..i]
for (int i = 1, k = 0; i < (int)pat.size(); i++) {
while (k > 0 && pat[i] != pat[k]) k = lps[k - 1];
if (pat[i] == pat[k]) k++;
lps[i] = k;
}
for (int i = 0, k = 0; i < (int)text.size(); i++) {
while (k > 0 && text[i] != pat[k]) k = lps[k - 1]; // fall back, never restart
if (text[i] == pat[k]) k++;
if (k == (int)pat.size()) return i - k + 1;
}
return -1;
} function strStr(text, pat) {
if (!pat) return 0;
const lps = new Array(pat.length).fill(0); // lps[i]: longest prefix = suffix of pat[0..i]
for (let i = 1, k = 0; i < pat.length; i++) {
while (k > 0 && pat[i] !== pat[k]) k = lps[k - 1];
if (pat[i] === pat[k]) k++;
lps[i] = k;
}
for (let i = 0, k = 0; i < text.length; i++) {
while (k > 0 && text[i] !== pat[k]) k = lps[k - 1]; // fall back, never restart
if (text[i] === pat[k]) k++;
if (k === pat.length) return i - k + 1;
}
return -1;
} The variations
-
1The prefix function
lps of the whole string answers "longest prefix that is also a suffix" directly: it is lps[n − 1].
-
2Find a pattern in a text
Run the same fall-back loop over the text. When k reaches the pattern length you found a match ending at i.
-
3More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Starting the lps loop at i = 0: lps[0] is always 0 because the prefix must be proper.
- Falling back with
k = lps[k]instead oflps[k - 1].
Lesson done
Next: Math and number theory →Mark it done once you can write the template from memory and you have solved the worked examples yourself.