Sub topic 10
Tries: prefix search over strings
This chapter assumes you know Python dictionaries, recursion, and the cost of hash lookups from the earlier chapters. A trie (also called a prefix tree) is a tree where each edge is labeled with one character. A path from the root spells a prefix, and a flag on a node marks where a complete word ends.
The problem a trie solves
Suppose you build autocomplete for a list of 100,000 words. A user types "pre" and you must return every word that starts with "pre".
A set or dictionary answers "is this exact word present?" in O(1) on average. It cannot answer prefix questions without scanning every key, which costs O(n × k) for n words of length k. A sorted list with binary search can find a prefix range, but inserts shift elements. A trie walks one node per character, so finding a prefix costs O(m), where m is the prefix length. That cost does not depend on how many words are stored.
The words "car" and "cat" share the path c, a. Shared prefixes are stored once.
A working implementation
Each node holds a dictionary from character to child node, plus an end-of-word flag.
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())
node.is_word = True
def _find(self, prefix):
node = self.root
for ch in prefix:
node = node.children.get(ch)
if node is None:
return None
return node
def contains(self, word):
node = self._find(word)
return node is not None and node.is_word
def starts_with(self, prefix):
return self._find(prefix) is not None
def words_with_prefix(self, prefix):
start = self._find(prefix)
results = []
if start is None:
return results
stack = [(start, prefix)]
while stack:
node, text = stack.pop()
if node.is_word:
results.append(text)
for ch, child in node.children.items():
stack.append((child, text + ch))
return sorted(results)
trie = Trie()
for w in ["car", "card", "care", "cat", "do"]:
trie.insert(w)
print(trie.contains("car")) # True
print(trie.contains("ca")) # False, a prefix but not a word
print(trie.starts_with("ca")) # True
print(trie.words_with_prefix("car")) # ['car', 'card', 'care']Note that contains("ca") is false while starts_with("ca") is true. The is_word flag is what separates them.
Costs
| Operation | Trie | Set of strings |
|---|---|---|
| Insert word of length m | O(m) | O(m) average (hashing reads the string) |
| Exact lookup | O(m) | O(m) average |
| Prefix existence | O(m) | O(n × m) scan |
| List all words with a prefix | O(m + size of the output subtree) | O(n × m) scan |
For exact lookup alone, a set is simpler and usually faster. Choose a trie only when prefix queries matter.
Trade-offs and gotchas
- Memory. Each node is a Python object with its own dictionary. A trie of many words with few shared prefixes can use far more memory than a set of the same strings.
- Locality. Following child pointers jumps around memory, so constant factors are worse than the O(m) suggests (see the memory layout chapter).
- Alphabet size. A dictionary per node handles any character. A fixed array of 26 slots is faster for lowercase ASCII but wastes space on sparse nodes.
- Alternatives. If the data is static, a sorted list plus
bisectcan find the range of words with a prefix using far less memory. If you only need a few matches, a trie's advantage shrinks.
Exercise
You store 50,000 product names and must show suggestions after each keystroke. Names are added throughout the day. Why is a set a poor fit, and what would you use?
Show answer
A set only tests exact membership, so each keystroke would need a scan of all 50,000 names to find prefix matches. A trie finds the prefix node in O(m) and then collects only the matching words, and it supports inserting new names cheaply. A sorted list with bisect would also work for prefix ranges but makes frequent inserts costly.
Exercise
In the implementation above, what would go wrong if you removed the is_word flag and returned True from contains whenever the path exists?
Show answer
contains("ca") would return True even though only "car", "card", "care" and "cat" were inserted. Every prefix of a stored word would be reported as a word.