Tries
A trie (pronounced "try", from retrieval), also called a prefix tree, stores a set of strings so that all strings with a common prefix share the same path from the root. Each edge is labelled with a character; a path from the root spells a prefix, and nodes are marked where a complete word ends.
(root)
/ \
c d
| |
a o
/ \ |
r* t* g*
|
t* words: car, cart, cat, dog (* = end of a word)Tries answer questions that hash sets can't answer efficiently, such as "which words start with ca?", which is exactly what autocomplete, spell checkers and IP routing tables need.
A trie node
Each node holds a dictionary from character to child node and a flag that says whether a word ends here.
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode()) # create the path if needed
node.is_word = True
def _walk(self, text):
node = self.root
for ch in text:
node = node.children.get(ch)
if node is None:
return None
return node
def contains(self, word):
node = self._walk(word)
return node is not None and node.is_word
def has_prefix(self, prefix):
return self._walk(prefix) is not None
t = Trie()
for w in ["car", "cart", "cat", "dog"]:
t.insert(w)
print(t.contains("car"), t.contains("ca"), t.contains("cow"))
print(t.has_prefix("ca"), t.has_prefix("do"), t.has_prefix("x"))True False False
True True False
"ca" is a prefix in the trie but not a word: the node exists, but its is_word flag is False.
Cost does not depend on the number of words
Inserting or looking up a word of length L visits exactly L nodes, whether the trie holds ten words or ten million. A sorted list needs O(L log n) (binary search with string comparisons), and a hash set needs O(L) to hash the word but can't do prefix queries.
class TrieNode:
def __init__(self):
self.children, self.is_word = {}, False
root = TrieNode()
words = ["tea", "ten", "tent", "team", "teapot", "to", "toe", "ton"]
created = 0
for w in words:
node = root
for ch in w:
if ch not in node.children:
node.children[ch] = TrieNode()
created += 1
node = node.children[ch]
node.is_word = True
letters = sum(len(w) for w in words)
print(f"{len(words)} words, {letters} letters, but only {created} nodes (shared prefixes)")8 words, 28 letters, but only 12 nodes (shared prefixes)
Autocomplete
To list all words with a given prefix, walk down to the prefix's node and then collect every word in its subtree with a DFS. Visiting children in sorted order returns the suggestions alphabetically:
class TrieNode:
def __init__(self):
self.children, self.is_word = {}, False
class Trie:
def __init__(self, words=()):
self.root = TrieNode()
for w in words:
node = self.root
for ch in w:
node = node.children.setdefault(ch, TrieNode())
node.is_word = True
def complete(self, prefix, limit=10):
node = self.root
for ch in prefix:
if ch not in node.children:
return []
node = node.children[ch]
results = []
def dfs(n, path):
if len(results) >= limit:
return
if n.is_word:
results.append(prefix + path)
for ch in sorted(n.children):
dfs(n.children[ch], path + ch)
dfs(node, "")
return results
commands = Trie(["git add", "git commit", "git checkout", "git cherry-pick",
"git clone", "git push", "grep", "gzip"])
print(commands.complete("git c"))
print(commands.complete("git ch"))
print(commands.complete("g", limit=3))
print(commands.complete("npm"))['git checkout', 'git cherry-pick', 'git clone', 'git commit']
['git checkout', 'git cherry-pick']
['git add', 'git checkout', 'git cherry-pick']
[]
Deleting a word
To delete, clear the word's is_word flag, then remove nodes that no longer lead to any word, walking back up from the end (a post-order cleanup):
class TrieNode:
def __init__(self):
self.children, self.is_word = {}, False
def insert(root, word):
node = root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_word = True
def delete(node, word, i=0):
"""Returns True if `node` became useless and can be removed by its parent."""
if i == len(word):
node.is_word = False
else:
child = node.children.get(word[i])
if child and delete(child, word, i + 1):
del node.children[word[i]]
return not node.is_word and not node.children
def all_words(node, path=""):
out = [path] if node.is_word else []
for ch in sorted(node.children):
out += all_words(node.children[ch], path + ch)
return out
def count_nodes(node):
return 1 + sum(count_nodes(c) for c in node.children.values())
root = TrieNode()
for w in ["car", "cart", "cat"]:
insert(root, w)
print(all_words(root), count_nodes(root), "nodes")
delete(root, "cart")
print(all_words(root), count_nodes(root), "nodes")
delete(root, "car")
print(all_words(root), count_nodes(root), "nodes")['car', 'cart', 'cat'] 6 nodes
['car', 'cat'] 5 nodes
['cat'] 4 nodes
Deleting cart removes its last t node, which led to no other word. Deleting car clears the flag on the r node; that node has no children left, so it is removed too, while c and a stay because they still lead to cat.
Complexity
| Operation | Trie | Hash set | Sorted list |
|---|---|---|---|
insert / lookup (word length L) |
O(L) |
O(L) average |
O(L log n) lookup, O(n) insert |
| all words with a prefix | O(P + output) |
O(n · L) (check every word) |
O(L log n + output) |
| memory | can be large (one node per distinct prefix) | compact | compact |
Tip: When memory matters, a compressed trie (radix tree) merges chains of single-child nodes into one edge labelled with a whole substring.
Test yourself
What does a path from the root of a trie represent?
- A sorted list
- A prefix of one or more stored words
- A hash value
- A word's length
How many nodes are visited to look up a word of length 6 in a trie holding a million words?
- 1
- At most 6 (plus the root)
- About 20
- A million
Which task is a trie especially good at compared with a hash set?
- Checking exact membership
- Listing all words that start with a prefix
- Storing integers
- Sorting numbers