Sub topic 4
Searching for Words and Prefixes
This chapter assumes you know Python dictionaries, basic string iteration, and the trie node and insert method from the previous chapters. Here you will add the two read operations: exact word search and prefix check.
One walk, two questions
Both queries start the same way. You begin at the root and follow one child per character. If a child is missing at any step, the string is not in the trie as a path, and you can stop.
The queries differ only at the end of the walk:
- Exact search asks: is there a word that is exactly this string? The final node must exist and its
is_endflag must beTrue. - Prefix check asks: does any stored word start with this string? The final node only has to exist.
Because the two operations share the walk, it is written once, in a helper that returns the node where the string ends, or None.
The path for "ca" exists, but the node for a is not marked as an end. So starts_with("ca") is true and search("ca") is false.
The implementation
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = 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_end = 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 search(self, word):
node = self._find(word)
return node is not None and node.is_end
def starts_with(self, prefix):
return self._find(prefix) is not None
t = Trie()
for w in ["car", "card", "care", "cat"]:
t.insert(w)
print(t.search("car")) # True
print(t.search("ca")) # False: path exists, but no word ends here
print(t.starts_with("ca")) # True
print(t.search("cart")) # False: no child 't' under "car"
print(t.starts_with("dog")) # False: no child 'd' under the root_find uses children.get(ch) instead of children[ch]. The get call returns None for a missing key, so the loop can exit early without a KeyError. Early exit also means a failed lookup often costs less than the full length of the string.
Common errors
- Skipping the end check in
search. Ifsearchreturnsnode is not None, it behaves likestarts_with. Searching for"ca"would wrongly returnTrue. - Returning the node instead of a boolean.
node and node.is_endcan returnNoneor a node object when you wantedTrueorFalse. Thenode is not None and node.is_endform always gives a boolean. - Mutating while searching. Using
setdefaultin_findwould create nodes during a read. Reads should not change the trie, which is why_findusesget. - Forgetting the empty string.
_find("")returns the root, sostarts_with("")is alwaysTrue, even on an empty trie.search("")isTrueonly if you inserted"", which setsroot.is_end.
Cost
Each step of the walk is one dictionary lookup, which takes O(1) on average. A query for a string of length L therefore takes O(L) time. The number of stored words does not appear in that cost. A trie with a million words answers a five-character query in about five steps. Only the length of the query matters.
Exercise
A trie contains only the words "tea" and "ten". What do search("te"), startswith("te"), search("tea") and startswith("tex") return, and why?
Show answer
search("te") is False, because the node for "e" exists but is not marked as a word end. startswith("te") is True, because the path t-e exists. search("tea") is True, because the path exists and the last node is marked as a word end. startswith("tex") is False, because the node for "e" has no child "x", so _find returns None.