208. Implement Trie (Prefix Tree)
Asked at 20Apple53Microsoft46Bloomberg45Amazon37Google36Meta35MongoDB100X94Docusign93General Motors65Grammarly60Nutanix60Oracle52Roblox51Uber50Citadel47Lyft43Snowflake39Goldman Sachs28TikTok26
Problem
Implement a Trie (prefix tree) with insert(word), search(word) (was this exact word inserted?) and startsWith(prefix) (was any word with this prefix inserted?).
Example: insert("apple") → search("apple") = true, search("app") = false, startsWith("app") = true
Constraints: lowercase letters; up to 3·10⁴ calls.
Walk/create child nodes char by char. search needs end at the last node; startsWith only needs the path to exist.
Complexity: O(L) per operation.
class Trie:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["$"] = True # end marker
def _walk(self, s):
node = self.root
for ch in s:
if ch not in node:
return None
node = node[ch]
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and "$" in node
def startsWith(self, prefix: str) -> bool:
return self._walk(prefix) is not None
t = Trie()
t.insert("apple")
assert t.search("apple") and not t.search("app") and t.startsWith("app")
t.insert("app")
assert t.search("app")
class Trie {
private static class Node { Node[] next = new Node[26]; boolean end; }
private final Node root = new Node();
public void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.end = true;
}
private Node walk(String s) {
Node n = root;
for (char c : s.toCharArray()) if ((n = n.next[c - 'a']) == null) return null;
return n;
}
public boolean search(String word) { Node n = walk(word); return n != null && n.end; }
public boolean startsWith(String prefix) { return walk(prefix) != null; }
}
type Trie struct {
children [26]*Trie
end bool // a word ends here
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
node := this
for i := 0; i < len(word); i++ {
c := word[i] - 'a'
if node.children[c] == nil {
node.children[c] = &Trie{}
}
node = node.children[c]
}
node.end = true
}
func (this *Trie) walk(s string) *Trie {
node := this
for i := 0; i < len(s) && node != nil; i++ {
node = node.children[s[i]-'a']
}
return node
}
func (this *Trie) Search(word string) bool {
node := this.walk(word)
return node != nil && node.end
}
func (this *Trie) StartsWith(prefix string) bool {
return this.walk(prefix) != nil
}