Type "tra" into the search box of an online shop, and suggestions appear right away: trainer, tray, trailer. They appear as fast as you type, even though the list holds hundreds of thousands of words.
One of the structures behind a feature like this is a trie (said "try"): a tree for storing words, one letter per node. A tree is a branching structure: there's one node at the top (the root), and each node can have several children. In a trie, words that start the same way (their first letters are the same) share the same path from the root. It's like a dictionary you open letter by letter: t, tr, tra, and then every word starting with "tra" is right there. In a trie, each of those letters is one node, and "tra" is the path root, t, r, a.
One letter per node
When a word goes in (insert), the trie walks down from the root letter by letter. If a node for that letter already exists on the path, that node is reused. If not, a new node is created. This table inserts three words, in order:
| insert | Nodes reused | New nodes |
|---|---|---|
| trainer | none | 7: t, r, a, i, n, e, r |
| tray | 3: t, r, a | 1: y |
| trailer | 4: t, r, a, i | 3: l, e, r |
That's 11 letter nodes for 18 letters (the root isn't counted, because the root holds no letter). The saving comes from the shared starts: "tra" is shared by all three words, and "trai" by trainer and trailer. The more words share a start, the more nodes you save.
This code makes a trie, then inserts the three words:
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (const letter of word) {
if (!node.children[letter]) {
node.children[letter] = new TrieNode();
}
node = node.children[letter];
}
node.isEnd = true;
}
search(word) {
let node = this.root;
for (const letter of word) {
if (!node.children[letter]) return false;
node = node.children[letter];
}
return node.isEnd;
}
startsWith(prefix) {
let node = this.root;
for (const letter of prefix) {
if (!node.children[letter]) return false;
node = node.children[letter];
}
return true;
}
}
const trie = new Trie();
trie.insert("trainer");
trie.insert("tray");
trie.insert("trailer");
console.log(trie.search("tray")); // true
console.log(trie.search("tra")); // false
console.log(trie.startsWith("trai")); // true
console.log(trie.startsWith("bo")); // false
TrieNodeis a class (a blueprint for objects) for one node. It holds two things:children, an object that maps a letter to its child node, andisEnd, a mark that says a word ends at this node.inserttakes the letters ofwordone by one (for (const letter of word)) and walks down from the root throughchildren. If there's no child for that letter yet, it's created first withnew TrieNode(). At the last letter's node,isEndis set totrue.searchwalks down the same way. If a letter isn't found inchildren, the answer isfalse. If every letter is there, the answer isnode.isEnd.startsWithchecks a start of a word (prefix). It works exactly the same, but if every letter of the prefix is found, the answer istrue, without looking atisEnd.
All three are O(m), m being the length of the word or prefix: a word twice as long takes twice as many steps. How many words the trie holds doesn't matter.
search and startsWith: what isEnd is for
Guess first: the trie above holds trainer, tray and trailer. Does search("trai") answer true or false?
The answer is false. The path t, r, a, i does exist in the trie, because trainer and trailer go through it. But no word ends at that i node, so its isEnd is false. startsWith("trai"), however, answers true. A prefix that exists isn't necessarily a word.
It works the other way too: a word can be the start of another word. Insert "tea" and "teapot", and search("tea") and startsWith("tea") are both true. The reason: the a node at the end of "tea" has isEnd set to true, and it also has a child (the p of "teapot").
When to use a trie
A trie fits autocomplete (suggesting words as you type) and prefix searches best: walk down to the prefix's node, and every matching word is under that node. Spell checking fits too: search makes sure the word exists, and startsWith checks whether any word has a given start. If you only ever check whole words, a Set is simpler and uses less memory.
⚠️ Words that go missing, and a prefix taken for a word
- Forgetting
isEnd = trueat the end ofinsert. Everysearchbecomesfalse, because no node is marked as the end of a word. - A
searchthat saystrueas soon as the path exists. That's howstartsWithworks.searchhas to returnnode.isEnd. - Creating a new node without checking.
node.children[letter] = new TrieNode()without theifoverwrites the old node, and words you already inserted disappear. - Upper and lower case take different paths. "Tray" and "tray" count as two words. Convert to lower case with
toLowerCase()beforeinsertandsearch.
TL;DR: A trie is a tree that stores words one letter per node, and words with the same start share nodes. insert walks down letter by letter, creates the nodes that are missing, then marks the last one with isEnd = true (a word ends here). search (check a whole word) returns the isEnd of the last letter's node, so a prefix (the start of a word) that isn't a whole word, like "trai" from trainer, answers false. startsWith (check a start) answers true if every letter of the prefix can be followed. All of them are O(length of the word). Use a trie for autocomplete (suggesting words as you type) and prefix searches. To check whole words only, a Set is enough.
⚡ One letter per node
Write:
insert(word) {
let node = this.root;
for (const letter of word) {
if (!node.children[letter]) {
node.children[letter] = new TrieNode();
}
node = node.children[letter];
}
node.isEnd = true;
}
Meaning: A trie is a tree that stores words, one letter per node, starting from the root (the node at the top). Each node keeps its children in children, with letters as keys. insert (a method of the Trie class) walks down from the root letter by letter, and creates a new node with new TrieNode() when there's no child for that letter yet. Then it marks the last node with isEnd = true, which means a word ends there. Words with the same start share nodes: trainer, tray and trailer need only 11 letter nodes for 18 letters.
⚡ A prefix isn't necessarily a word
Guess first: search checks whether a whole word is in the trie. A trie holds trainer, tray and trailer. Does search("trai") answer true or false?
false. The path t, r, a, i is there, but no word ends at that i node, so its isEnd is false. It's startsWith("trai") (check a start) that answers true.
Meaning: search returns node.isEnd, while startsWith answers true if every letter of the prefix (the start of a word) can be followed. Both are O(length of the word), however many words the trie holds.
⚡ When to use a trie
Meaning: A trie fits autocomplete (suggesting words as you type) and prefix searches best: walk down to the prefix's node, and every matching word is under that node. If you only check whole words, a Set is simpler.