Reference solution
One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.
#include <bits/stdc++.h>
using namespace std;
struct Trie {
struct Node { int next[26]; bool end; Node() : end(false) { fill(next, next+26, -1); } };
vector<Node> nodes;
Trie() { nodes.push_back(Node()); }
void insert(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (nodes[cur].next[idx] == -1) {
nodes[cur].next[idx] = nodes.size();
nodes.push_back(Node());
}
cur = nodes[cur].next[idx];
}
nodes[cur].end = true;
}
bool search(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (nodes[cur].next[idx] == -1) return false;
cur = nodes[cur].next[idx];
}
return nodes[cur].end;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q; cin >> q;
Trie trie;
while (q--) {
string op, word; cin >> op >> word;
if (op == "insert") trie.insert(word);
else if (op == "search") cout << (trie.search(word) ? "YES" : "NO") << '\n';
}
return 0;
}