Implement Trie (Prefix Tree)
The problem
Section titled “The problem”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 with the prefix.
insert("apple") search("apple") -> true search("app") -> falsestartsWith("app") -> true insert("app") search("app") -> true“app” is a prefix of “apple” but was not inserted as a word, so search says false
until it is.
Key insight
Section titled “Key insight”A hash set answers search in O(L) for a word of length L, but startsWith forces you
to scan every stored word. Brute force is O(total characters) per query.
Store the words as a tree instead: one character per edge, so words with the same
beginning share one path. Each node keeps a map from character to child, plus a flag
saying “a word ends here”. All three operations are the same walk from the root. Insert
creates missing nodes and sets the flag at the end. search walks and checks the flag.
startsWith walks and only checks that the path exists.
Show solutionHide solution
class TrieNode: def __init__(self): self.children = {} # char -> TrieNode self.is_word = False
class Trie: def __init__(self): self.root = TrieNode()
def insert(self, word: str) -> None: node = self.root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.is_word = True
def search(self, word: str) -> bool: node = self._find(word) return node is not None and node.is_word
def starts_with(self, prefix: str) -> bool: return self._find(prefix) is not None
def _find(self, s: str): """Follow s from the root; return the node it ends on, or None.""" node = self.root for ch in s: if ch not in node.children: return None node = node.children[ch] return nodeclass TrieNode { children = new Map<string, TrieNode>(); // char -> TrieNode isWord = false;}
export class Trie { private root = new TrieNode();
insert(word: string): void { let node = this.root; for (const ch of word) { if (!node.children.has(ch)) node.children.set(ch, new TrieNode()); node = node.children.get(ch)!; } node.isWord = true; }
search(word: string): boolean { const node = this.find(word); return node !== null && node.isWord; }
startsWith(prefix: string): boolean { return this.find(prefix) !== null; }
// Follow s from the root; return the node it ends on, or null. private find(s: string): TrieNode | null { let node = this.root; for (const ch of s) { const next = node.children.get(ch); if (next === undefined) return null; node = next; } return node; }}import java.util.HashMap;import java.util.Map;
class TrieNode { Map<Character, TrieNode> children = new HashMap<>(); // char -> TrieNode boolean isWord = false;}
class Trie { private final TrieNode root = new TrieNode();
public void insert(String word) { TrieNode node = root; for (char ch : word.toCharArray()) { node = node.children.computeIfAbsent(ch, c -> new TrieNode()); } node.isWord = true; }
public boolean search(String word) { TrieNode node = find(word); return node != null && node.isWord; }
public boolean startsWith(String prefix) { return find(prefix) != null; }
// Follow s from the root; return the node it ends on, or null. private TrieNode find(String s) { TrieNode node = root; for (char ch : s.toCharArray()) { node = node.children.get(ch); if (node == null) return null; } return node; }}Complexity
Section titled “Complexity”- Time: O(L) — each of insert, search and startsWith touches one node per character of the argument, with O(1) map work per step (L = length of the word or prefix).
- Space: O(total chars) — at most one node per inserted character; shared prefixes cost nothing extra.
Watch out for
Section titled “Watch out for”- Search and startsWith differ only in the flag. Forgetting
is_wordmakessearch("app")return true after inserting only “apple”. - Set the flag on the last node, not on every node on the path. Otherwise every prefix looks like a word.
- Don’t build the node before checking. In
searchandstartsWith, never create children while walking; only insert may add nodes.
Variations
Section titled “Variations”Design Add and Search Words Data Structure (LeetCode 211)
Section titled “Design Add and Search Words Data Structure (LeetCode 211)”Same trie, but search accepts . as a wildcard for any one letter. The trick: on a
normal letter follow that child; on . try every child recursively (DFS). Insert is
unchanged.
Word Search II (LeetCode 212)
Section titled “Word Search II (LeetCode 212)”Find all words from a list that can be traced on a letter grid. The trick: put the words in a trie and run one DFS from each cell, walking the trie alongside the grid. Stop a path as soon as the trie has no child for the next letter; that pruning beats running Word Search once per word.
Replace Words (LeetCode 648)
Section titled “Replace Words (LeetCode 648)”Replace each word in a sentence with its shortest dictionary root. The trick: insert
the roots, then for each word walk the trie and return the prefix at the first node with
is_word set. If the walk dies first, keep the original word.