guest@cp-base:~/home/strings$
templates/kmp.cpp
compilable
$cat templates/kmp

KMP Algorithm

Knuth-Morris-Pratt pattern matching and prefix function in O(n + m).

[Strings]|
Jul 9, 2026
|explanatory_notes.md|
#kmp#pattern-matching#prefix-function#string
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_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
24
25
26
#include <bits/stdc++.h>
using namespace std;

vector<int> prefixFunction(const string &s) {
    int n = s.size();
    vector<int> pi(n);
    for (int i = 1; i < n; i++) {
        int j = pi[i - 1];
        while (j > 0 && s[i] != s[j])
            j = pi[j - 1];
        if (s[i] == s[j]) j++;
        pi[i] = j;
    }
    return pi;
}

vector<int> kmpSearch(const string &text, const string &pat) {
    string t = pat + "#" + text;
    vector<int> pi = prefixFunction(t);
    vector<int> matches;
    int m = pat.size();
    for (int i = m + 1; i < (int)t.size(); i++)
        if (pi[i] == m)
            matches.push_back(i - 2 * m);
    return matches;
}
26 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

KMP Algorithm

Linear-time pattern matching using the prefix function to avoid redundant comparisons.

Prefix Function

For each position ii, π[i]\pi[i] is the length of the longest proper prefix of s[0..i]s[0..i] that is also a suffix:

π[i]=max{k:s[0..k1]=s[ik+1..i],  k<i+1}\pi[i] = \max\{k : s[0..k-1] = s[i-k+1..i],\; k < i+1\}

Built in O(n)O(n) by maintaining j=π[i1]j = \pi[i-1] and falling back via j=π[j1]j = \pi[j-1] on mismatch.

Pattern Matching

  • Build t=p+#+st = p + \text{\#} + s (sentinel prevents false overlaps)

  • Compute π\pi on tt

  • Match at position i2pi - 2|p| in ss whenever π[i]=p\pi[i] = |p|
  • When to Use

  • Finding all occurrences of pattern pp in text ss

  • String periodicity — ss has period pp if π[s1]sp\pi[|s|-1] \ge |s| - p and psp \mid |s|

  • Computing the prefix function for DP on strings, automaton construction
  • Complexity

  • Time — O(n+m)O(n + m)

  • Space — O(n+m)O(n + m)