Retrieve Prefix Matches with Tries
Core idea
A trie stores strings as paths of character edges. A terminal marker distinguishes a complete key from an internal prefix. This nested dictionary uses None as a marker (character keys are strings). Insertion and prefix lookup take O(k) expected dictionary operations for k characters; listing completions also visits the matching subtree.
trie = {}for word in ['car', 'cart', 'cat']: node = trie for ch in word: node = node.setdefault(ch, {}) node[None] = Truenode = trie['c']['a']['r']print(None in node, 't' in node)print(None in trie['c']['a'])car is both a word and a prefix; ca is only a prefix.
Enumerate completions
trie = {'a': {'b': {None: True}, 'c': {None: True}}}def complete(node, prefix): if None in node: yield prefix for ch in sorted(k for k in node if k is not None): yield from complete(node[ch], prefix + ch)print(list(complete(trie['a'], 'a')))Start from the prefix node and walk its descendants in sorted order.
Common mistake
Prefix presence is not exact-key membership. A trie can use more memory than a hash table; normalize text only under an explicit policy.
Practice
Insert an empty key and two overlapping words; check exact membership and prefix matches separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tries
Check your understanding of tries.
What is printed?
node={'x':{None:True}}print(None in node)What is printed?
print(sorted(['cat','car']))What marks an exact word?
What extra work does listing completions require?