The Subsequence Automaton is a data structure that maintains a string in by maintaining a deterministic finite automaton that accepts and only accepts subsequences of .

Specifically, let be a function in such that

Lemma

For any in , equals the minimum in such that is a subsequence of if is a subsequence of , or otherwise.

Applying the lemma yields that is a deterministic finite automaton that accepts and only accepts subsequences of .

This requires space.

Build

Build builds a Subsequence Automaton for in time and space.

Algorithm

Lemma

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();
 
	next.assign(n + 1, {});
	for (char c : alphabet) {
		next[n][c] = -1;
	}
	for (int i = n - 1; i >= 0; i--) {
		for (char c : alphabet) {
			next[i][c] = c == s[i] ? i + 1 : next[i + 1][c];
		}
	}
}

Find

Find checks if is a subsequence of 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) {
		if (next[o][c] == -1) {
			return false;
		}
		o = next[o][c];
	}
	return true;
}