Tries
Start typing a word and your phone narrows the guesses with every letter. After two letters you are already on the right page for every word that starts that way. A trie stores words the same way, sharing each prefix once so a lookup only walks the letters you type.
2 · Watch
Tries in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Implement Trie (Prefix Tree)
or try
Up to 4 words of 1–6 letters (a–z), then | and a word to look up.Start with an empty root.Step 1 of 18. Empty trie, just a root node. 3 words to insert, then look up “ca”.
Step 1 of 18
solution.ts
class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
function insert(root: TrieNode, word: string) {
let node = 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;
}
function search(root: TrieNode, word: string, prefix = false) {
let node = root;
for (const ch of word) {
const next = node.children.get(ch);
if (!next) return false;
node = next;
}
return prefix || node.isWord;
}
▶ marks the line running now
4 · Your turn
0 of 3 problems solved
Start from this
let node = root;
for (const ch of word) {
// Make the path if this letter isn't there yet.
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch)!;
}
// Without this, "app" matches because of "apple".
node.isWord = true;Easy ways to go wrong
- Forgetting the end-of-word flag, so “app” matches because “apple” exists.
- Reaching for a trie when a plain set of words is enough.
- Not pruning used words in board searches, which repeats the work.
- Medium01
Implement Trie (Prefix Tree)
The one you just watched. Write it from memory.
Words with the same start share one path of letters.
- Time
- O(L)
- Space
- O(total letters)
- Medium02
Design Add and Search Words Data Structure
Trie search where “.” matches any letter at that spot.
Walk a tree of letters, and branch everywhere on a dot.
- Time
- O(26^L) worst
- Space
- O(total letters)
Also works with Backtracking.
- Hard03
Word Search II
Walk the board and the trie together, pruning dead letters.
A tree of all the words lets you search them at once and drop dead paths.
- Time
- O(m·n·3^L)
- Space
- O(total letters)
Also works with Backtracking.