Share the prefix, not the whole word.
Represent a vocabulary by shared prefixes and distinguish a word from a path.
01 Model the idea
A trie stores keys along character paths. Common prefixes share nodes, making prefix questions natural. A terminal marker distinguishes a complete word from a prefix that merely leads to longer words. The lookup cost depends primarily on key length, while storage depends on the amount of shared prefix structure and the representation used for child maps.
A complete word exists exactly when its path ends at a terminal node.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FOLLOW or create one child per character
MARK the final node as a complete key
FOR membership, require that terminal marker03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class Trie:
def __init__(self): self.root = {}
def insert(self, word):
node = self.root
for character in word: node = node.setdefault(character, {})
node[None] = True
def contains(self, word):
node = self.root
for character in word:
if character not in node: return False
node = node[character]
return None in node
trie = Trie()
trie.insert("code"); trie.insert("coder")
print(trie.contains("code"), trie.contains("cod"))True False
- 1
The example reserves None as a terminal key; actual characters are string keys, so the marker cannot collide with a character.
- 2
A path for cod exists, but its final node is not marked terminal. Exact-word lookup and prefix existence are different operations.
- 3
Use an explicit normalisation policy for case, accents, and Unicode before inserting and searching. A production autocomplete system also needs ranking, result limits, and memory-aware storage.
04 Count the cost
Expected O(L) for a key of L characters
O(total stored prefix nodes)
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Implement a prefix-existence check and distinguish it from exact membership.
Reveal one possible solution +
root = {}
for word in ["code", "coder"]:
node = root
for ch in word: node = node.setdefault(ch, {})
node[None] = True
node = root
for ch in "cod": node = node[ch]
print(bool(node), None in node)06 Check your reasoning
Why store a terminal marker?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.