Lesson 148 of 296
Tries
What you will learn
- What a trie is and what it is for
- Building insert, search and startsWith
- Autocomplete
- Word Search II
On this page
What is a trie?
A trie (from retrieval, usually said "try") is a tree for storing strings by their characters. Each node represents a prefix; each edge is one character. A flag marks nodes where a complete word ends.
Words: car, cart, cat, dog
(root)
/ \
c d
| |
a o
/ \ |
r* t* g*
|
t* * = end of a wordWords that share a prefix share the same path, so prefix searches are fast: checking a prefix of length L takes O(L), however many words are stored.
Uses: autocomplete, spell checkers, IP routing tables, word games.
Implement Trie
Problem (LeetCode 208): insert, search (exact word) and startsWith (any word with this prefix).
class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
class Trie {
private root = new TrieNode();
insert(word: string): void {
let node = this.root;
for (const ch of word) {
let next = node.children.get(ch);
if (next === undefined) {
next = new TrieNode();
node.children.set(ch, next);
}
node = next;
}
node.isWord = true;
}
search(word: string): boolean {
const node = this.findNode(word);
return node !== null && node.isWord;
}
startsWith(prefix: string): boolean {
return this.findNode(prefix) !== null;
}
wordsWithPrefix(prefix: string, limit = 10): string[] {
const start = this.findNode(prefix);
const results: string[] = [];
if (start === null) return results;
const collect = (node: TrieNode, path: string): void => {
if (results.length >= limit) return;
if (node.isWord) results.push(path);
for (const [ch, child] of node.children) collect(child, path + ch);
};
collect(start, prefix);
return results;
}
findNode(text: string): TrieNode | null {
let node = this.root;
for (const ch of text) {
const next = node.children.get(ch);
if (next === undefined) return null;
node = next;
}
return node;
}
}insert,searchandstartsWith: O(L) for length L.searchneedsisWord: inserting "cart" does not mean "car" was inserted, but "car" is a prefix.wordsWithPrefixis a simple autocomplete: walk to the prefix node, then collect words below it with DFS. Real autocomplete also ranks results (for example by popularity).- Space: up to O(total characters of all words). A
Mapper node handles any alphabet; an array of 26 is faster for lowercase letters only.
Word Search II (stretch)
Problem (LeetCode 212, hard): find all dictionary words in a letter grid (adjacent cells, each used once per word).
Running Word Search (Lesson 135) separately for every word repeats work. Instead, put all words in a trie and do one backtracking search from each cell, walking the trie at the same time. Stop a path as soon as its prefix is not in the trie.
function findWords(board: string[][], words: string[]): string[] {
const trie = new Trie();
for (const w of words) trie.insert(w);
const rows = board.length;
const cols = board[0]?.length ?? 0;
const found = new Set<string>();
function explore(r: number, c: number, node: TrieNode, path: string): void {
if (r < 0 || r >= rows || c < 0 || c >= cols) return;
const ch = board[r]![c]!;
const next = node.children.get(ch);
if (next === undefined) return;
const word = path + ch;
if (next.isWord) found.add(word);
board[r]![c] = "#";
explore(r + 1, c, next, word);
explore(r - 1, c, next, word);
explore(r, c + 1, next, word);
explore(r, c - 1, next, word);
board[r]![c] = ch;
}
const root = trie.findNode("")!;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) explore(r, c, root, "");
}
return [...found];
}findNode("") returns the root, because an empty prefix matches immediately. A "#" cell never matches a child, which stops paths from reusing cells.
How to say it in an interview
"A trie stores strings character by character so words sharing a prefix share a path; each node has a children map and an end-of-word flag. Insert, search and startsWith are O(length of the word), independent of how many words are stored. I use it for autocomplete: walk to the prefix node, then DFS to collect words. For Word Search II I insert all words into a trie and backtrack over the grid once, pruning any path whose prefix is not in the trie."
Key words
| Word | Meaning |
|---|---|
| Trie | A tree of characters for fast prefix lookups |
| Prefix | The start of a string |
| End-of-word flag | Marks a node where a complete word ends |
| Autocomplete | Suggesting words that start with typed text |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.