Tries and Prefixes
Share character paths while distinguishing a word from a prefix.
python, trie, prefixes, strings, dictionaryShare the beginning of words
A trie stores one edge per character along a path. Words that start alike share the path for that prefix. An end marker is needed because a path may exist without being a complete inserted word.
Python illustration
def insert(root, word):
node = root
for char in word:
node = node.setdefault(char, {})
node[None] = True
def contains(root, word):
node = root
for char in word:
if char not in node:
return False
node = node[char]
return None in node
trie = {}
insert(trie, "cat")
insert(trie, "car")
print(contains(trie, "cat"))
print(contains(trie, "ca"))
Prepared output: True, then False on separate lines.
See the reasoning
Follow shared prefix paths
Distinguish a path from a complete inserted word. This is a prepared demonstration, not live code execution.
Insert cat
- Shared prefixc → aCurrent focus
- Endingt: word
Mark t as the end of cat.
Exact words and costs
Following characters reaches the node for that prefix; the None marker
records whether the complete word was inserted. An empty word is supported
by marking the root. With expected O(1) dictionary operations, insertion and
lookup take O(m) expected time for a word of length m. The trie uses space
proportional to the number of distinct prefix nodes, with significant
dictionary overhead. Case, Unicode normalisation, prefix enumeration and
deletion require explicit application policies.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
