The Trie is a data structure that maintains a set of strings in by maintaining a deterministic finite automaton that accepts and only accepts strings in .

Specifically, let be the set of the prefixes of the strings in , be a function in satisfying

Then it is easy to prove that is a deterministic finite automaton that accepts and only accepts strings in .

This costs a space of .

Add

Add updates to in time and space.

Algorithm

Updating the values in that are changed by yields an algorithm that solves the problem in time and space.

void add(const std::string &s) {
	int o = 1;
	for (char c : s) {
		if (!next[o][c]) {
			next[o][c] = next.size();
			next.emplace_back();
			f.push_back(false);
		}
		o = next[o][c];
	}
	f[o] = true;
}

Find

Find checks if in time and space.

Algorithm

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

bool find(const std::string &s) {
	int o = 1;
	for (char c : s) {
		o = next[o][c];
	}
	return f[o];
}