Implement Trie (Prefix Tree)
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement a trie (also called a prefix tree, pronounced "try"): a structure that stores words so that looking up a word, or checking whether any word starts with some prefix, is fast.
Implement the class Trie:
new Trie()creates an empty trie.insert(word)addsword.search(word)returnstrueifwordwas inserted, otherwisefalse.startsWith(prefix)returnstrueif some inserted word starts withprefix.
Understand the problem
- A prefix is the beginning of a word:
"app"is a prefix of"apple". Every word is also a prefix of itself. searchneeds an exact word: after inserting only"apple",search("app")isfalse.startsWithonly needs some word to begin that way:startsWith("app")istrue.- Think of autocomplete: as you type
"app", it needs to quickly know which words start that way.
Example 1
ops: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
args: [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
expected: [null, null, true, false, true, null, true]search("apple")→true: it was inserted.search("app")→false: only"apple"was inserted so far.startsWith("app")→true:"apple"starts with"app".- After
insert("app"),search("app")→true.
How the tests work: each test is a sequence of calls. ops names each call (the first creates the object), args holds the arguments, and expected the return values (null for calls that return nothing).
Constraints
1 <= word.length, prefix.length <= 2000- Words and prefixes contain lowercase English letters only.
- At most
3 * 10^4calls in total.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Store words as paths in a tree where each step is one letter, and mark the nodes where a word ends; every operation is then a walk down the letters.
The naive approach (and why it's slow)
Keep all words in an array (or a set).
search(word): a set does this quickly. Fine.startsWith(prefix): you have to check every stored word to see if it starts with the prefix. With 30,000 words, that's slow for each call.
The key insight
Words that start the same way can share their beginning. Store the letters as a tree, where each edge is a letter:
This trie holds car, card and care. Each node has:
children: a map from a letter to the next node.isEnd:trueif a word ends at this node (the nodes marked "end").
Now every operation is just a walk down the letters, and its cost depends only on the length of the word, not on how many words are stored.
| Operation | Walk the letters... | Answer |
|---|---|---|
insert(word) | creating any missing child along the way | mark the last node isEnd |
search(word) | if a letter is missing, stop: false | the last node's isEnd |
startsWith(prefix) | if a letter is missing, stop: false | true (reaching the end is enough) |
Step by step
The calls from Example 1:
| Call | Walk | Result |
|---|---|---|
insert("apple") | create a → p → p → l → e, mark e as end | |
search("apple") | walk to e, which is an end | true |
search("app") | walk to the second p, which is not an end | false |
startsWith("app") | walk to the second p: the path exists | true |
insert("app") | the path exists; mark the second p as an end | |
search("app") | walk to the second p, now an end | true |
The code
The reference solution is below, with comments on every important line.
How fast is it?
With L = the length of the word or prefix:
- Time: O(L) per call, no matter how many words are stored.
- Memory: O(total letters inserted) in the worst case (when no beginnings are shared).
Common mistakes
- Forgetting
isEnd. Without it,search("app")would wrongly returntrueafter inserting only"apple". - Making
searchreturntruejust because the path exists. That'sstartsWith.searchalso needsisEnd. - Storing the letter in the node instead of on the edge and getting confused about the root. The root is empty; the letters are the keys of
children.
Going deeper
- With only lowercase letters,
childrencan be an array of 26 slots instead of a map: slightly faster, more memory. - Tries power autocomplete, spell checkers and IP routing tables. You'll use one again in Design Add and Search Words and Word Search II.
Reference solution
class TrieNode {
children = new Map() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class Trie {
root = new TrieNode() // the root holds no letter
/**
* @param {string} word
* @return {void}
*/
insert(word) {
let node = this.root
for (const char of word) {
// Follow the letter, creating the node if this path doesn't exist yet.
if (!node.children.has(char)) node.children.set(char, new TrieNode())
node = node.children.get(char)
}
node.isEnd = true // mark that a word ends here
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
// The path must exist AND a word must end exactly there.
return this.#walk(word)?.isEnd ?? false
}
/**
* @param {string} prefix
* @return {boolean}
*/
startsWith(prefix) {
// Just reaching the end of the prefix is enough.
return this.#walk(prefix) !== null
}
// Follow the letters from the root. Returns the last node, or null if a letter is missing.
#walk(text) {
let node = this.root
for (const char of text) {
node = node.children.get(char)
if (!node) return null
}
return node
}
}class TrieNode {
children = new Map<string, TrieNode>() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class Trie {
private root = new TrieNode() // the root holds no letter
insert(word: string): void {
let node = this.root
for (const char of word) {
// Follow the letter, creating the node if this path doesn't exist yet.
let child = node.children.get(char)
if (!child) {
child = new TrieNode()
node.children.set(char, child)
}
node = child
}
node.isEnd = true // mark that a word ends here
}
search(word: string): boolean {
// The path must exist AND a word must end exactly there.
return this.walk(word)?.isEnd ?? false
}
startsWith(prefix: string): boolean {
// Just reaching the end of the prefix is enough.
return this.walk(prefix) !== null
}
// Follow the letters from the root. Returns the last node, or null if a letter is missing.
private walk(text: string): TrieNode | null {
let node: TrieNode | undefined = this.root
for (const char of text) {
node = node.children.get(char)
if (!node) return null
}
return node
}
}class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {} # letter → next node
self.is_end = False # does a whole word end at this node?
class Trie:
def __init__(self):
self.root = TrieNode() # the root holds no letter
def insert(self, word: str) -> None:
node = self.root
for char in word:
# Follow the letter, creating the node if this path doesn't exist yet.
node = node.children.setdefault(char, TrieNode())
node.is_end = True # mark that a word ends here
def search(self, word: str) -> bool:
# The path must exist AND a word must end exactly there.
node = self._walk(word)
return node is not None and node.is_end
def starts_with(self, prefix: str) -> bool:
# Just reaching the end of the prefix is enough.
return self._walk(prefix) is not None
# Follow the letters from the root. Returns the last node, or None if a letter is missing.
def _walk(self, text: str) -> TrieNode | None:
node = self.root
for char in text:
node = node.children.get(char)
if node is None:
return None
return node