$cat templates/kmp

KMP Algorithm

Knuth-Morris-Pratt pattern matching

O(n + m)Strings
Jun 21, 2026
#string#pattern-matching#kmp
$cat code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
vector<int> buildLPS(const string &p) {
    int m = p.size();
    vector<int> lps(m);
    for (int i = 1, len = 0; i < m;) {
        if (p[i] == p[len]) lps[i++] = ++len;
        else if (len) len = lps[len - 1];
        else lps[i++] = 0;
    }
    return lps;
}
vector<int> kmp(const string &s, const string &p) {
    auto lps = buildLPS(p);
    vector<int> matches;
    for (int i = 0, j = 0; i < (int)s.size();) {
        if (s[i] == p[j]) i++, j++;
        if (j == p.size()) { matches.push_back(i - j); j = lps[j - 1]; }
        else if (i < (int)s.size() && s[i] != p[j]) {
            if (j) j = lps[j - 1];
            else i++;
        }
    }
    return matches;
}
23 linesutf-8
$cat notes.txt

Computes LPS array then matches in linear time.