Back to solutions
Implement Trie (Prefix Tree)
MediumTriesImplement a trie supporting insert, search for a full word, and startsWith for a prefix.
Constraints
- 1 <= word.length <= 2000
- Lowercase English letters
26-way children with end flag
Time O(L) per operationSpace O(total characters)
Each node holds up to 26 child links and a flag marking the end of a word. Insert walks/creates nodes; search and startsWith walk the path, with search also checking the end flag.
#include <bits/stdc++.h>
using namespace std;
class Trie {
struct Node { Node* next[26] = {}; bool end = false; };
Node* root = new Node();
public:
void insert(string word) {
Node* cur = root;
for (char c : word) {
if (!cur->next[c - 'a']) cur->next[c - 'a'] = new Node();
cur = cur->next[c - 'a'];
}
cur->end = true;
}
bool search(string word) {
Node* n = find(word);
return n && n->end;
}
bool startsWith(string prefix) { return find(prefix) != nullptr; }
private:
Node* find(const string& s) {
Node* cur = root;
for (char c : s) {
if (!cur->next[c - 'a']) return nullptr;
cur = cur->next[c - 'a'];
}
return cur;
}
};