Tries · Pattern 1 of 3
Trie basics: insert, search, prefixes and autocomplete
Walk the word letter by letter, creating missing children on insert and stopping at a missing child on search. Counts in the nodes, wildcards and autocomplete are small additions to the same walk.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Insert words and ask whether a word or a prefix exists
- How many words start with a prefix, with inserts and erases
- Suggestions after each typed letter
- A
.that matches any letter
The template
class Trie {
class Node { Node[] next = new Node[26]; boolean end; }
Node root = new Node();
void insert(String word) {
Node cur = root;
for (char c : word.toCharArray()) {
if (cur.next[c - 'a'] == null) cur.next[c - 'a'] = new Node(); // create the path
cur = cur.next[c - 'a'];
}
cur.end = true; // a word ends here
}
Node walk(String s) { // the node for s, or null
Node cur = root;
for (char c : s.toCharArray()) {
cur = cur.next[c - 'a'];
if (cur == null) return null;
}
return cur;
}
boolean search(String word) { Node n = walk(word); return n != null && n.end; }
boolean startsWith(String prefix) { return walk(prefix) != null; }
} class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for c in word:
node = node.children.setdefault(c, TrieNode()) # create the path
node.end = True # a word ends here
def _walk(self, s): # the node for s, or None
node = self.root
for c in s:
node = node.children.get(c)
if node is None:
return None
return node
def search(self, word):
node = self._walk(word)
return node is not None and node.end
def starts_with(self, prefix):
return self._walk(prefix) is not None class Trie {
struct Node { Node* next[26] = {}; bool end = false; };
Node* root = new Node();
Node* walk(const string& s) { // the node for s, or nullptr
Node* cur = root;
for (char c : s) {
cur = cur->next[c - 'a'];
if (!cur) return nullptr;
}
return cur;
}
public:
void insert(const string& word) {
Node* cur = root;
for (char c : word) {
if (!cur->next[c - 'a']) cur->next[c - 'a'] = new Node(); // create the path
cur = cur->next[c - 'a'];
}
cur->end = true; // a word ends here
}
bool search(const string& word) { Node* n = walk(word); return n && n->end; }
bool startsWith(const string& prefix) { return walk(prefix) != nullptr; }
}; class Trie {
constructor() {
this.root = { next: new Map(), end: false };
}
insert(word) {
let cur = this.root;
for (const c of word) {
if (!cur.next.has(c)) cur.next.set(c, { next: new Map(), end: false }); // create the path
cur = cur.next.get(c);
}
cur.end = true; // a word ends here
}
walk(s) { // the node for s, or null
let cur = this.root;
for (const c of s) {
cur = cur.next.get(c);
if (!cur) return null;
}
return cur;
}
search(word) { const n = this.walk(word); return n !== null && n.end; }
startsWith(prefix) { return this.walk(prefix) !== null; }
} The variations
-
1Build a trie
Insert creates missing children; search and starts-with walk and stop at a missing child. Add two counters per node (words passing through, words ending here) to count prefixes and support erase. The longest common prefix of two numbers is how far the second walks in a trie of the first list's digits.
Now you solve -
2Wildcard search with DFS
Search recursively with the node and the position in the word. A letter follows one child; a
.tries every child and succeeds if any branch does. At the end of the word, check the end flag. -
3Autocomplete
Walk the typed prefix once, keeping the node as each letter is added. The suggestions are the first words below that node: visit children in letter order, or keep the top few words in each node. Ranking by how often a sentence was typed is the same walk with counts.
Now you solve -
4A trie of path parts
Split a path like
/a/b/con/and treat each name as one "letter", with a map of children per node. A file is a node that also holds content; listing a directory is its children in sorted order.
Mistakes to avoid
- Returning true from
searchfor a word that is only a prefix: "app" after inserting only "apple". - Wildcard search that returns after trying the first child: try every child and return true if any succeeds.
- Autocomplete that collects every word below the node and then sorts: visit children in letter order and stop after k words.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.