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 start the same way share the same path from the root. You implement a class Trie with three methods:
Insert(string word)adds a word.Search(string word)returnstrueonly if exactly that word was inserted before.StartsWith(string 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 because "app" was never inserted as a word, while StartsWith("app") is true. After Insert("app"), Search("app") becomes true. Inserting the same word twice changes nothing. The words and prefixes are 1 to 30 lowercase letters, and each operation should take O(L) time, where L is the length of the word or prefix.
The lesson has you write two classes: TrieNode, for one node, and Trie, which owns the root and the three methods.
Approach: one node per prefix, a flag for word ends
Storing the words in a list makes every query scan the list. A hash set answers Search quickly, but it can't answer StartsWith without checking every word. A trie answers both by walking down from the root, one letter per level, so the cost depends only on the length of the word asked about, not on how many words are stored.
Each TrieNode has two fields:
children, a dictionary from a letter to the child node for that letter. It holds only the letters that some word actually uses.isEnd, a flag that istruewhen an inserted word ends at this node.
The flag is needed because a node doesn't tell you whether it ends a word. After inserting "apple", the nodes for "app" and "apple" both exist, but only the "apple" node has isEnd set. The root stands for the empty prefix, and an empty trie is a root with no children.
All three operations walk the same way. Insert creates any missing nodes along the path and marks the last one. Search and StartsWith create nothing: they return false as soon as a letter has no child. They differ only at the end. Search returns the last node's isEnd, while StartsWith returns true, because every node in the trie lies on the path of some inserted word.
Inserting "apple" creates 5 nodes below the root, so the trie has 6 nodes. Inserting "app" afterwards creates none and only sets a flag, so the count stays 6. Inserting "apt" adds one node for "t" and makes it 7.
Step by step
- Declare
childreninTrieNodeas apublic Dictionary<char, TrieNode>set to a new empty dictionary. Fields are private unless markedpublic, andTriehas to reach this one. - Declare
isEndas apublic boolset tofalse. - Declare
rootinTrieas a newTrieNode. - In
Insert, startnodeatrootand loop over the letters ofwordwithforeach. - If
node.childrenhas no keyc, test withContainsKeyand store a newTrieNodeundernode.children[c]. No earlier word went this way, so create the path. - Move down with
node = node.children[c]. The child exists now, whether it was already there or was just created. - After the loop, set
node.isEnd = true. This marks the whole word as inserted. - In
Search, walk the same way but returnfalsewhen a letter has no child, and finish withreturn node.isEnd. Reaching the node isn't enough: the path for "app" exists after inserting "apple", but no word ends there. - In
StartsWith, walk once more, returnfalseat a missing letter, and finish withreturn true.
The solution in C#
class TrieNode {
public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
public bool isEnd = false;
}
class Trie {
TrieNode root = new TrieNode();
public void Insert(string word) {
TrieNode node = root;
foreach (char c in word) {
if (!node.children.ContainsKey(c)) {
node.children[c] = new TrieNode();
}
node = node.children[c];
}
node.isEnd = true;
}
public bool Search(string word) {
TrieNode node = root;
foreach (char c in word) {
if (!node.children.ContainsKey(c)) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
public bool StartsWith(string prefix) {
TrieNode node = root;
foreach (char c in prefix) {
if (!node.children.ContainsKey(c)) {
return false;
}
node = node.children[c];
}
return true;
}
}
The C# details worth knowing:
- A missing key throws. Reading
node.children[c]for a key that isn't there throwsKeyNotFoundException, unlike a JavaHashMapor a Pythondict.get, which givenullor a default. That is why every read is guarded byContainsKey. Assigning withnode.children[c] = ...never throws: it adds the key if needed. TryGetValueis the alternative.node.children.TryGetValue(c, out TrieNode next)checks and reads in one lookup. The lesson's version does two lookups per letter, which is fine at these sizes.foreach (char c in word)visits the characters of a string in order. Acharis a valid dictionary key.- Visibility.
roothas no modifier, so it is private toTrie.childrenandisEndarepublicso thatTrie's methods can use them. The method names are PascalCase,Insert,SearchandStartsWith, as the starter code has them. Code ported from Java or Python often usesinsertandstartsWith, which don't match. - Printing a
boolwithConsole.WriteLinegivesTrueorFalse, with capital letters. The values are still the C# keywordstrueandfalse. Dictionaryneedsusing System.Collections.Generic;at the top of a standalone file.
Complexity
Time: O(L) per operation. Each operation does one dictionary lookup, which takes constant time on average, for each of the L letters. The number of words stored doesn't matter.
Space: O(N) in total, where N is the number of nodes created. In the worst case, when no two words share a prefix, that is the total length of all inserted words. Shared prefixes are stored once.
Edge cases and common mistakes
- Empty trie.
Search("a")andStartsWith("a")both returnfalse, since the root has no children. - A word that is a prefix of another. With "car" and "cart" inserted,
Search("car")is true andStartsWith("car")is true.Search("ca")is false andStartsWith("ca")is true. - A prefix that was never a word. With "dog" inserted,
Search("do")is false, andStartsWith("dogs")is false because the walk runs out of nodes. - Duplicate inserts. Inserting "dog" twice creates the nodes once and sets the same flag twice.
- Returning
trueat the end ofSearch. That would makeSearch("app")true after inserting only "apple". The final answer must benode.isEnd. - Forgetting to set
isEndinInsert. EverySearchwould then return false, even for inserted words. - Creating nodes while searching. Using
node.children[c] = new TrieNode()inSearchwould grow the trie on each query and make absent words look like prefixes later. - Reading a missing child without
ContainsKey. The walk would throwKeyNotFoundExceptionon the first word that isn't present.
Testing
- Insert "apple", then
Search("apple"),Search("app"),StartsWith("app"), insert "app",Search("app")give true, false, true, true. - Insert "car" and "cart", then
StartsWith("ca"),Search("ca"),StartsWith("cat"),Search("cart")give true, false, false, true. - Insert "dog" twice, then
Search("dog"),StartsWith("dog"),Search("do"),StartsWith("dogs"),Search("dogs")give true, true, false, false, false. - On an empty trie,
Search("a")andStartsWith("a")give false and false.
