Sub topic 6
Autocomplete: collecting every word under a prefix
This chapter assumes you know depth-first search, recursion, Python dictionaries, and the Trie class from the earlier chapters (TrieNode with children and is_end, plus insert, _find and search).
The two-step idea
Autocomplete answers one question: given a prefix, which stored words start with it? A trie splits this into two steps.
- Walk down from the root, following the prefix one character at a time. This is the same walk
_finddoes. If it falls off the trie, no word has this prefix. - From the node where the walk ended, traverse its whole subtree. Every node with
is_endset marks a word. Its text is the prefix plus the characters along the path from that node.
Step 1 costs O(P) for a prefix of length P. Step 2 depends on how much of the trie lies below the prefix node, not on how many words the trie holds in total.
For the prefix car, step 1 stops at the node r. Step 2 visits r, d and e and reports car, card and care. The t branch is never touched.
The implementation
Add this method to the Trie class:
def autocomplete(self, prefix, limit=10):
results = []
start = self._find(prefix)
if start is None:
return results
def dfs(node, path):
if len(results) >= limit:
return
if node.is_end:
results.append(prefix + "".join(path))
for ch in sorted(node.children):
path.append(ch)
dfs(node.children[ch], path)
path.pop()
if len(results) >= limit:
return
dfs(start, [])
return resultsUsage:
t = Trie()
for w in ["car", "card", "care", "cat"]:
t.insert(w)
print(t.autocomplete("car")) # ['car', 'card', 'care']
print(t.autocomplete("ca", 2)) # ['car', 'card']
print(t.autocomplete("dog")) # []
print(t.search("ca")) # False
print(t.starts_with("ca")) # TrueHow the traversal works
pathis a shared list. It holds the characters from the prefix node down to the current node. The code appends a character before recursing and pops it afterward. This is backtracking. It avoids building a new string at every step.- The word is built only at a hit. When
node.is_endis true,prefix + "".join(path)produces the full word. The emptypathat the start node means the prefix itself is returned if it is a word, ascaris above. sorted(node.children)gives alphabetical order. A dictionary yields keys in insertion order, so without sorting, the output order would depend on the order you inserted words. Because each node is visited before its children and children are visited in sorted order, shorter words come before their extensions:carbeforecard.limitstops the search early. The check at the top ofdfsand the check after each recursive call let the traversal unwind as soon as enough words are found. This matters when a short prefix such asasits above millions of words.
Cost
Let P be the prefix length, k the number of words returned, and S the number of nodes visited.
| Part | Cost |
|---|---|
| Find the prefix node | O(P) |
| Traverse the subtree | O(S), plus sorting at each node |
| With a small `limit` | Stops after about k words are found |
Without a limit, the cost grows with the size of the subtree. With a limit, the traversal can still visit many nodes that lead to no word, such as a long chain of nodes before the first is_end. A limit bounds the output, not strictly the work.
Common errors
- Forgetting the prefix node itself. If you start the traversal at the children of the prefix node, you miss the case where the prefix is a stored word.
- Joining the wrong string. If
pathalready included the prefix, you would outputcarcar. Herepathstarts empty at the prefix node, so the prefix is added once. - Not copying at a hit. Appending the
pathlist itself toresultsstores a reference that later changes. Build a string at the hit, as the code does. - Relying on dictionary order. Without
sorted, results are not alphabetical. - Deep recursion. Python's default recursion limit is about 1000 frames. Very long words can exceed it, so use an explicit stack for such data.
Exercise
In the trie holding "car", "card", "care" and "cat", what does autocomplete("ca", limit=3) return, and why is "cat" last?
Show answer
It returns ['car', 'card', 'care']. The traversal visits children of "a" in sorted order: "r" comes before "t". The whole "r" subtree is explored first and yields three words, which reaches the limit, so "cat" is never visited.
Exercise
Why does the traversal check the limit again after each recursive call, not only at the top of dfs?
Show answer
Once a deep call fills the results, the loop in the parent would otherwise continue and start recursing into the next child before the top check stops it. The check after the call exits the loop immediately and avoids that extra work, so the traversal unwinds right away.