The Knuth-Morris-Pratt Automaton is a data structure that maintains a string in by maintaining a deterministic finite automaton that accepts and only accepts strings containing as a suffix.

Specifically, let

and let be a function in such that

Lemma

Applying the lemma yields that is a deterministic finite automaton that accepts and only accepts strings containing as a suffix.

This requires space.

Build

Build builds a Knuth-Morris-Pratt Automaton for in time and space.

Algorithm

  1. Let . Apply the Knuth-Morris-Pratt Algorithm to find .

Lemma

  1. For , apply the lemma to find for each in .

This algorithm solves the problem in time and space.

void build(const std::string &s) {
	n = s.length();
	auto pi = knuth_morris_pratt(n, s);
 
	next.assign(n + 1, {});
	for (int i = 0; i <= n; i++) {
		for (char c : alphabet) {
			next[i][c] = i < n && c == s[i] ? i + 1 : next[pi[i]][c];
		}
	}
}

Find

Find checks if contains as a suffix in time and space.

Algorithm

Running on yields an algorithm that solves the problem in time and space.

bool find(const std::string &t) {
	int o = 0;
	for (char c : t) {
		o = next[o][c];
	}
	return o == n;
}