Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) is LeetCode 208 (Medium). Build a class Trie with three methods:
insert(word)stores a word.search(word)returns true only if that exact word was inserted.startsWith(prefix)returns true if any inserted word begins withprefix.
All strings are lowercase letters, up to 2,000 long, and there are at most 3 × 10⁴ calls in total.
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 10⁴ calls in total will be made to insert, search, and startsWith.
Intuition
Store each word one letter per level, so words that begin the same way share the same path. Every node then stands for a prefix: the letters on the way down from the root to it. A node needs two things:
- Children: a map (or a 26-slot array) from the next letter to the child node.
- End flag: a boolean saying that a whole word stops at this node.
Walking a string from the root takes one step per letter, however many words are stored. startsWith only needs that walk to succeed. search also needs the end flag, because the path for "an" exists inside "ant" even if "an" itself was never inserted.
Reach for a trie when the questions are about prefixes rather than whole strings: autocomplete, spell checkers, Word Search II, Replace Words. A hash set answers "is this exact word stored?" but has no fast way to answer "does any stored word start with this?".
Approach
Before reading on, insert "ant" into an empty trie, then call search("an") and startsWith("an"). What does each return, and which single piece of data tells them apart? Aim for O(L) per call, where L is the length of the string.
Give each node children and an end flag
A node holds children, mapping a letter to the next node, and is_end, false by default. The root stands for the empty prefix. The C++ and Java versions use a 26-slot array instead of a map, which works because the input is only lowercase letters.
Insert: walk down, creating missing nodes
Start at the root. For each letter, create the child only if it is missing, then step into it. After the last letter, set is_end = True on that node, because the path alone cannot say whether a word ends here or a longer word just passes through.
Share one walk for both queries
_find(s) follows the letters of s from the root and returns the node it reaches, or None the moment a child is missing. A missing child means no stored word starts with that many letters of s, so there is no point reading further.
search checks the flag, startsWith does not
search returns true only if _find reached a node and that node has is_end set. startsWith returns true whenever _find reached a node, since every node in the trie lies on the path of at least one inserted word.
Code in Python, C++ and Java
Common pitfalls
search that ignores the end flag
def search(self, word):
return self._find(word) is not Nonedef search(self, word):
node = self._find(word)
return node is not None and node.is_endThis is startsWith under another name. After insert("apple"), search("app") returns true, because the nodes for "app" exist inside "apple".
Setting the end flag inside the loop
for ch in word:
...
node = node.children[ch]
node.is_end = Truefor ch in word:
...
node = node.children[ch]
node.is_end = TrueEvery prefix of the word gets marked as a word. After insert("apple"), search("a") and search("app") both return true. Only the node after the last letter should be marked.
Creating a child even when it exists (array version)
node.children[c] = new Node(); node = node.children[c];
if (node.children[c] == null) node.children[c] = new Node(); node = node.children[c];
The new node replaces the old one and everything below it. Insert "ant" then "an", and the t node is thrown away, so search("ant") returns false.
Edge cases
Inserting "an" after "ant" creates no nodes: every letter already exists, so only the flag on the n node changes.
The walk reuses every node and the flag is already true, so the trie is unchanged.
A word counts as a prefix of itself, so startsWith("ant") returns true after insert("ant").
Complexity
Implement Trie (Prefix Tree) FAQ
Hash map or 26-slot array for the children?
The array gives a direct index with no hashing, but every node pays for 26 slots even when it has one child. A map stores only the letters that exist and works for any alphabet. With lowercase-only input both pass; the array is usually faster and the map smaller on sparse tries.
Why not just keep the words in a hash set?
A set handles search well, but startsWith would have to check every stored word: up to 3 × 10⁴ words of up to 2,000 letters, on every call. Putting every prefix into a second set makes it fast but stores up to 2,000 strings for a single 2,000-letter word, which is O(L²) memory.
How do you delete a word from a trie?
Walk to the word's last node and clear is_end. To free memory as well, remove nodes on the way back up while they have no children and no end flag. Implement Trie II (problem 1804) asks for this, with counts stored at each node.