Sub topic 11
Storing Counts and Values in Nodes
This chapter assumes you have read the earlier chapters. You should know how a trie node holds a children dictionary and an is_end flag. You should also know how insert, _find and autocomplete work, and be comfortable with recursion and Big-O notation.
Why extra data in a node
A plain trie answers one question: is this string in the set? Many real tasks need more. You may want to know how many words start with a prefix. You may want to attach a definition, a price, or a popularity score to a word. You can answer these by adding fields to TrieNode. The path through the trie stays the same. Only the data stored along it changes.
There are two common kinds of metadata:
- Prefix counts. Each node records how many stored words pass through it. This answers "how many words start with this prefix?" in O(L) time, where L is the prefix length.
- Values. The node that ends a word stores a payload. The trie then works like a dictionary with string keys.
Prefix counts
Add a count field to each node. During insert, increment it on every node you visit. The count at a node is the number of stored words that have that node's path as a prefix.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
self.count = 0 # words passing through this node
self.value = None # payload for a word ending here
class Trie:
def __init__(self):
self.root = TrieNode()
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 search(self, word):
node = self._find(word)
return node is not None and node.is_end
def insert(self, word, value=None):
if self.search(word):
self._find(word).value = value
return
node = self.root
node.count += 1
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.count += 1
node.is_end = True
node.value = value
def count_prefix(self, prefix):
node = self._find(prefix)
return node.count if node else 0
def get(self, word, default=None):
node = self._find(word)
if node is not None and node.is_end:
return node.value
return default
t = Trie()
for w in ["car", "card", "care", "cat"]:
t.insert(w)
print(t.count_prefix("car")) # 3
print(t.count_prefix("ca")) # 4
print(t.count_prefix("dog")) # 0Notice that insert first checks whether the word already exists. Without that check, inserting a duplicate would inflate every count along the path. This is the most common bug in count-based tries.
The same discipline applies to deletion. If you remove a word, decrement count on every node along its path, and only when the word was actually present. Pruning then has a simpler rule: a node whose count drops to 0 holds no words and can be removed along with its subtree.
Values: using the trie as a map
The value field turns the trie into a map from strings to arbitrary data. In the code above, insert("cat", 5) stores 5 at the node for cat, and get("cat") returns it. Re-inserting an existing key overwrites its value without changing counts.
Keep is_end even when you store values. A value of None is ambiguous, because it could mean "no word here" or "the word's value is None". The is_end flag removes that ambiguity.
Metadata for ranking autocomplete
Autocomplete from an earlier chapter returns words in alphabetical order. Real systems usually rank by popularity. Store a score as the value, collect the words under the prefix, and sort by score:
def top_completions(trie, prefix, k=3):
start = trie._find(prefix)
if start is None:
return []
found = []
def dfs(node, path):
if node.is_end:
found.append((node.value, prefix + "".join(path)))
for ch, child in node.children.items():
path.append(ch)
dfs(child, path)
path.pop()
dfs(start, [])
found.sort(key=lambda pair: (-pair[0], pair[1]))
return [word for _, word in found[:k]]
t = Trie()
for word, score in [("car", 40), ("card", 90), ("care", 70), ("cat", 55)]:
t.insert(word, score)
print(top_completions(t, "ca")) # ['card', 'care', 'cat']This visits every word under the prefix, so it costs O(S) for the subtree size S, plus a sort. For a short prefix such as "a", S can be huge. A faster design stores the top-k words at each node and updates them on insert. That uses more memory and makes updates more expensive. It pays off when reads far outnumber writes.
Trade-offs
| Metadata | Query it enables | Extra cost |
|---|---|---|
| `count` per node | Words per prefix in O(L) | One integer per node, update on insert and delete |
| `value` at word end | String-keyed map | One reference per node |
| Top-k list per node | Ranked completions without scanning | Memory and update work grow with k |
Exercise
A trie holds "car", "card" and "cat" with prefix counts. You call insert("card") a second time and your insert does not check for existing words. What is count_prefix("car") afterward, and what should it be?
Show answer
It returns 4, because the second insert increments every node on the path again. It should stay 2 (car and card). Check whether the word exists before incrementing, or return early when it does.
Exercise
Why keep an is_end flag when each word-ending node already has a value field?
Show answer
A stored value can be None or any falsy value, so checking the value cannot tell "no word here" from "word with an empty value". is_end records word membership directly.