Back to track
#49 Medium Intermediate

Trie Basics

Open the editor

Problem

Implement insert and search in a trie.

Constraints

1 <= N <= 200000
Lowercase letters only

Hints

  1. 1

    Children map

  2. 2

    End-of-word flag

Worked solution

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;
}

© 2026 ChitChat