Tries: insert, search, prefix
A trie stores words character by character along edges, with markers where words end. Insert, search and prefix queries take time proportional to word length.
Before you start: Hash sets and maps in practice: counting, lookup, deduplication.
The idea
A trie stores words letter by letter. Words that start the same share one path from the root.
The words cat, cap and car all begin with ca, so they share two nodes instead of storing ca three times.
Intuition
To find the words that start with ca, a plain list checks every word. The work grows with the list.
In a trie the prefix ca is one node. Every word below that node starts with ca.
A lookup reads one node per letter, however many words are stored. The price is one node per distinct letter position.
How it works
A prefix query only needs the path. startsWith ca is true here, even though ca is not a word.
Complexity
A lookup reads one node per letter, so a word of L letters costs L steps. Adding more words does not change that.
Insert and prefix queries follow the same single path. Space is one node per distinct prefix, at most the total letters stored.
Pitfalls
Only cart is stored. Searching car follows a full path but stops on a node without an end mark, so it is false.
Without end marks, every prefix of a stored word would look like a word.
Variations
Store a count on each node to know how many words share a prefix. Autocomplete and word search build on this.
Code
Pseudocode
insert(word)
node ← root
for each ch in word
if node.child[ch] = null: node.child[ch] ← new node
node ← node.child[ch]
node.isEnd ← true
find(word)
node ← root
for each ch in word
if node.child[ch] = null: return null
node ← node.child[ch]
return node
search(word)
node ← find(word)
return node ≠ null and node.isEnd
startsWith(prefix)
return find(prefix) ≠ null
Python
def insert(root, word):
node = root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def find(root, word):
node = root
for ch in word:
if ch not in node.children:
return None
node = node.children[ch]
return node
def search(root, word):
node = find(root, word)
return node is not None and node.is_end
def starts_with(root, prefix):
return find(root, prefix) is not None
JavaScript
function insert(root, word) {
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.isEnd = true;
}
function find(root, word) {
let node = root;
for (const ch of word) {
if (!node.children.has(ch)) return null;
node = node.children.get(ch);
}
return node;
}
function search(root, word) {
const node = find(root, word);
return node !== null && node.isEnd;
}
function startsWith(root, prefix) {
return find(root, prefix) !== null;
}
Cost at a glance
| Access | n/a |
|---|---|
| Search | O(L) for a word of length L |
| Insert | O(L) |
| Delete | O(L) |
| Space | O(total characters × alphabet) |
Practice problems (7)
Node count Warm-up
Words are inserted into an empty trie one at a time. After each word, type how many nodes the trie has, not counting the root.
Which trie holds these words? Warm-up
A trie stores the words to, tea and ten. Pick the picture that shows it.
Starts-with Warm-up
Given a list of words and a prefix, return how many words start with prefix. A word that appears twice counts twice.
Store a count in every node: the number of words that pass through it.
Implement a trie Standard
Build a trie and run a list of commands on it. insert W adds the word W. search W is true only when W was inserted as a whole word. startsWith W is true when some inserted word begins with W.
Return the results of the search and startsWith commands in order, as the text true or false. insert produces no output.
Longest common prefix Standard
Return the longest prefix shared by every word in words. Return the empty string when there is none, or when words is empty.
Insert all words into a trie. The common prefix is the path from the root where each node has exactly one child and no word ends.
Trace a search Standard
Follow a search for ca in a trie that holds cat, cap, car and dog. Answer each question before the step plays.
Word dictionary with wildcard Challenge
Build a word dictionary and run a list of commands. add W stores the word W. search P is true when some stored word matches the pattern P. In P, a dot . matches any single letter, and every other letter must match itself. The word must have the same length as P.
Return the results of the search commands in order, as the text true or false.
Related topics
Next on the path: Trie applications: autocomplete, word search, XOR maximum