Problem overview
A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each child adds one more letter to it. Words that begin the same way share the same path from the root, so asking about a word or a prefix takes time that depends only on its length.
The class Trie has three operations:
insert(word)adds a word;search(word)returnstrueonly if exactly that word was inserted;startsWith(prefix)returnstrueif some inserted word begins withprefix. A word counts as a prefix of itself.
After insert("apple"), search("apple") is true but search("app") is false, while startsWith("app") is true. After insert("app"), search("app") becomes true. Inserting the same word twice changes nothing. Words and prefixes are 1 to 30 lowercase letters, and each operation should run in O(L) time for a word of length L.
Approach: one node per prefix
A set of words would answer search in one lookup, but startsWith would have to scan every word. A trie answers both by walking from the root, one letter per level.
Each node has two things:
children: a map from the next letter to the child node;isEnd: a flag that is true when an inserted word ends at this node.
The root stands for the empty prefix, so an empty trie is one root with no children. Inserting "apple" creates a chain of five nodes below the root, for a, ap, app, appl and apple, and marks the last one as an end. The node for app exists but is not marked, which is exactly why search("app") is false at that point. Inserting "app" later only sets that node's flag.
The three operations are the same walk with different endings. Counting the nodes, root included, gives: 1 node when empty, 6 after "apple", still 6 after "app" (only a flag changes), and 7 after "apt", which shares a and ap and adds only apt.
Step by step
- Define the node.
TrieNodeholdschildren, anunordered_map<char, TrieNode*>that starts empty, andbool isEnd = false. - Create the root in
TriewithTrieNode* root = new TrieNode();. The values in the map are pointers too: each child is made withnewand stays alive for as long as the trie uses it. - In
insert, start at the root. A pointernodewalks down the trie. - Loop over the letters. A range-based
forgives eachchar cofword. - Create a missing child.
node->children.count(c)is 1 if the key exists and 0 if not. When it is 0, storenew TrieNode()underc. - Move down to
node->children[c]. The child exists by now, new or old. - Mark the end. After the loop,
nodeis the node of the whole word, and settingisEndthere is what makes the word count as inserted. - In
search, walk the same way without creating anything. If a letter has no child, returnfalse. - Return
node->isEndat the end. Reaching the node is not enough: the path for"app"exists after inserting"apple", but no word ends there. - In
startsWith, do the same walk and returnfalseat a missing letter. If the loop finishes, returntrue: every node lies on the path of some inserted word, so a complete path means some word starts with the prefix. The flag doesn't matter.
The solution in C++
struct TrieNode {
unordered_map<char, TrieNode*> children;
bool isEnd = false;
};
class Trie {
public:
TrieNode* root = new TrieNode();
void insert(string word) {
TrieNode* node = root;
for (char c : word) {
if (!node->children.count(c)) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->isEnd = true;
}
bool search(string word) {
TrieNode* node = root;
for (char c : word) {
if (!node->children.count(c)) {
return false;
}
node = node->children[c];
}
return node->isEnd;
}
bool startsWith(string prefix) {
TrieNode* node = root;
for (char c : prefix) {
if (!node->children.count(c)) {
return false;
}
node = node->children[c];
}
return true;
}
};
The C++ details worth a closer look:
- Why
countbefore[].children[c]on a missing key inserts a null pointer for it. Ininsertthat would be harmless, because the code overwrites it, but insearchandstartsWithit would add junk entries, and the next step would dereference a null pointer. Testing withcountfirst keeps lookups from changing the map. The lookups after the check are safe because the key exists. - Default member values.
bool isEnd = false;andTrieNode* root = new TrieNode();are initialised where they are declared, so no constructor is needed. The compiler's default constructor creates an empty trie, which is the state the statement calls "creates an empty trie". - Memory. Every
newallocates a node that the code never deletes, so the memory lives until the program ends. That is fine for a program that builds one trie, but a long-running program would need a destructor that deletes the children recursively, orunique_ptrin the map. - Arrays of 26 instead of a map.
TrieNode* next[26]indexed byc - 'a'is faster and uses a fixed amount of memory per node, at the price of 26 pointers in every node, even those with one child. The map pays only for the children that exist. - Passing strings by value. The methods take
stringby value, which copies up to 30 characters per call. It is cheap here.const string&avoids the copy.
Complexity
Let L be the length of the word or prefix.
Time: O(L) per operation. Each operation visits one node per letter and does a constant amount of work at each: an average O(1) hash lookup in an unordered_map, and at most one allocation when inserting. The cost doesn't depend on how many words the trie already holds.
Space: O(total letters inserted) in the worst case. Each inserted word adds at most one node per letter, and words that share a prefix share nodes. With at most 100,000 operations of up to 30 letters, that is at most 3,000,000 nodes.
Edge cases and common mistakes
- Empty trie.
search("a")andstartsWith("a")are bothfalse: the root has no children, so the walk stops at the first letter. - A word that is a prefix of another. After inserting
"car"and"cart",search("car")andsearch("cart")are bothtrue, because the node forcarand the node forcartboth haveisEndset. - Prefix that is not a word. With
"car"and"cart"inserted,startsWith("ca")istrueandsearch("ca")isfalse. - A prefix longer than any word. After inserting
"dog",startsWith("dogs")andsearch("dogs")are bothfalse: the walk runs out of children ats. - Duplicate inserts. A second
insert("dog")finds every node already there, and sets a flag that is alreadytrue. - Returning
truefromsearchat the end of the path. This confuses a word with a prefix of a longer word. TheisEndcheck is what separates the two. - Forgetting to set
isEndininsert. Thensearchwould befalsefor every word, thoughstartsWithwould still work. - Returning
node->isEndfromstartsWith. That would make it behave likesearch, sostartsWith("app")would befalseafter inserting only"apple".
Testing
insert("apple"), thensearch("apple"),search("app")andstartsWith("app")givetrue,false,true. Afterinsert("app"),search("app")givestrue.insert("car"),insert("cart"), thenstartsWith("ca"),search("ca"),startsWith("cat")andsearch("cart")givetrue,false,false,true.insert("dog")twice, thensearch("dog"),startsWith("dog"),search("do"),startsWith("dogs")andsearch("dogs")givetrue,true,false,false,false.- On an empty trie,
search("a")andstartsWith("a")givefalseandfalse.
