A trie (prefix tree) stores strings character by character. Insert and search take O(length of word). Used for autocomplete, spell check and prefix search.
struct TrieNode {
TrieNode *child[26] = {};
bool isEnd = false;
};
void insert(TrieNode *root, const string &w) {
for (char c : w) {
int i = c - 'a';
if (!root->child[i]) root->child[i] = new TrieNode();
root = root->child[i];
}
root->isEnd = true;
}
bool search(TrieNode *root, const string &w) {
for (char c : w) {
root = root->child[c - 'a'];
if (!root) return false;
}
return root->isEnd;
}