Implement Trie (Prefix Tree) (LeetCode 208): Solution and Explanation
Build a prefix tree that supports three operations: insert a word, check whether an exact word was inserted, and check whether any inserted word starts with a given prefix.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious design is to keep the words in a hash set. Exact lookups are then fast, but prefix queries are not: to answer startsWith, you would have to compare the prefix against every stored word, which costs time proportional to the whole dictionary.
A trie flips the storage around so that shared prefixes are stored once. Each node represents the string spelled by the path from the root to it, and its children are the possible next characters. The words apple and app share the nodes for a, p and p, and only branch after that. With this shape, answering whether anything starts with a prefix is just walking down the tree one character at a time, and the cost depends only on the length of the prefix, not on how many words are stored.
The one detail that trips people up is telling a full word apart from a prefix. After inserting apple, the path for app exists in the tree, but app was never inserted. So each node carries an is_end flag that is set only on the last node of an inserted word. Search walks the path and then checks that flag, while startsWith only needs the path to exist.
The reference code stores children in a dictionary keyed by character. That handles any alphabet and only allocates entries for characters that actually appear. A fixed array of 26 slots is a common alternative when the input is lowercase letters only.
Approach: Trie with dictionary children
- Define
TrieNodewith achildrendictionary and anis_endflag set to false, and give theTriean empty root node. - For
insert, start at the root and, for each character, create a child node if it is missing, then move into it. - After the last character of the word, set
node.is_end = Trueto mark that a complete word ends there. - For
search, walk the same way, returning false as soon as a character has no child, and at the end returnnode.is_end. - For
startsWith, walk the prefix the same way, but return true once every character is matched, regardless of the flag.
Step-by-step example
insert(apple), search(apple), search(app), startsWith(app), insert(app), search(app)
insert(apple)creates the chain a, p, p, l, e under the root and marks the e node withis_end = True.search(apple)follows all five characters and reaches the e node, whose flag is true, so it returns true.search(app)follows a, p, p and stops at the second p node. Its flag is false, so it returns false.startsWith(app)follows the same three nodes successfully and returns true without checking the flag.insert(app)walks the existing a, p, p nodes without creating anything and sets the flag on the second p node.search(app)now reaches a node whose flag is true and returns true.
Code: Python, Java, C++
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.is_end = False
5
6class Trie:
7 def __init__(self):
8 self.root = TrieNode()
9
10 def insert(self, word: str) -> None:
11 node = self.root
12 for char in word:
13 if char not in node.children:
14 node.children[char] = TrieNode()
15 node = node.children[char]
16 node.is_end = True
17
18 def search(self, word: str) -> bool:
19 node = self.root
20 for char in word:
21 if char not in node.children:
22 return False
23 node = node.children[char]
24 return node.is_end
25
26 def startsWith(self, prefix: str) -> bool:
27 node = self.root
28 for char in prefix:
29 if char not in node.children:
30 return False
31 node = node.children[char]
32 return True1class TrieNode {
2 Map<Character, TrieNode> children = new HashMap<>();
3 boolean isEnd = false;
4}
5
6class Trie {
7 private TrieNode root;
8
9 public Trie() {
10 root = new TrieNode();
11 }
12
13 public void insert(String word) {
14 TrieNode node = root;
15 for (char c : word.toCharArray()) {
16 node.children.putIfAbsent(c, new TrieNode());
17 node = node.children.get(c);
18 }
19 node.isEnd = true;
20 }
21
22 public boolean search(String word) {
23 TrieNode node = root;
24 for (char c : word.toCharArray()) {
25 if (!node.children.containsKey(c)) return false;
26 node = node.children.get(c);
27 }
28 return node.isEnd;
29 }
30
31 public boolean startsWith(String prefix) {
32 TrieNode node = root;
33 for (char c : prefix.toCharArray()) {
34 if (!node.children.containsKey(c)) return false;
35 node = node.children.get(c);
36 }
37 return true;
38 }
39}1class TrieNode {
2public:
3 unordered_map<char, TrieNode*> children;
4 bool isEnd = false;
5};
6
7class Trie {
8private:
9 TrieNode* root;
10public:
11 Trie() { root = new TrieNode(); }
12
13 void insert(string word) {
14 TrieNode* node = root;
15 for (char c : word) {
16 if (!node->children.count(c)) {
17 node->children[c] = new TrieNode();
18 }
19 node = node->children[c];
20 }
21 node->isEnd = true;
22 }
23
24 bool search(string word) {
25 TrieNode* node = root;
26 for (char c : word) {
27 if (!node->children.count(c)) return false;
28 node = node->children[c];
29 }
30 return node->isEnd;
31 }
32
33 bool startsWith(string prefix) {
34 TrieNode* node = root;
35 for (char c : prefix) {
36 if (!node->children.count(c)) return false;
37 node = node->children[c];
38 }
39 return true;
40 }
41};Time and space complexity
O(L) per operation
Each of insert, search and startsWith does one dictionary lookup or insertion per character of its input, where L is the length of the word or prefix. The number of stored words does not matter.
O(T)
T is the total number of characters across all inserted words. In the worst case no prefixes are shared and every character gets its own node; shared prefixes reduce this.
Other approaches
Fixed array of 26 children (time O(L) per operation, space O(26 × T))
Give each node an array of 26 child slots indexed by ord(ch) - ord('a'). Lookups avoid hashing and are slightly faster, but every node reserves 26 slots even if it only has one child, so memory use is higher.
Hash set of words and prefixes (time O(L²) insert, O(L) query, space O(sum of L²))
Store each word in one set and every prefix of every word in another. Queries become single set lookups, but inserting a word of length L stores L prefix strings with a combined length of O(L²).
Common mistakes
- Returning true from
searchjust because the path exists. Without checkingis_end, a search for app succeeds after inserting only apple. - Setting
is_endon every node along the path during insert, which makes every prefix look like an inserted word. - Creating a new node even when the child already exists, which overwrites an existing subtree and silently deletes previously inserted words.
- Checking
is_endinstartsWith. A prefix query should succeed whenever the path exists, whether or not a word ends there.
Frequently asked questions
What is the difference between search and startsWith in a trie?
Both walk the tree character by character. search also requires that the final node is marked as the end of a word, while startsWith only requires that the path exists.
What is the time complexity of a trie?
Insert, search and prefix search all run in O(L), where L is the length of the input string. They do not depend on how many words the trie holds.
Should trie children be a hash map or an array?
An array of 26 is a bit faster for lowercase English and simple to index, but it wastes memory on sparse nodes. A hash map handles any character set and only stores children that exist.
When is a trie better than a hash set?
When you need prefix queries, autocomplete or wildcard matching. A hash set answers exact lookups well but has no efficient way to find all words that share a prefix.