Maintain a word collection supporting both exact whole-word lookup and lookup by prefix.
Problem
Input. Calls to insert(word), search(word), and starts_with(prefix) on an initially empty Trie.
Output. Insertion stores a word; search reports exact membership, while starts_with reports whether the prefix can be followed.
Rules. Match Python string code points exactly, without case conversion or normalization.
A prefix is not automatically a stored word. Repeated insertion has no additional effect.
Empty strings are supported. The empty prefix returns True even before any insertion.
Example. After inserting "app" and "apple", search("app") returns True.
The call search("ap") returns False, while starts_with("ap") returns True.
Picture
The root spells the empty prefix.
Each character labels one edge to a child dictionary.
Following the shared path reaches a, ap, app, appl, then apple.
Inserting app creates three edges and marks its final node.
Inserting apple reuses those edges, adds two more, and marks the new final node.
The node for app remains terminal despite having children.
The root-to-node edge labels uniquely spell that node’s prefix.
Reaching a dictionary therefore certifies a path, not necessarily complete-word membership.
The None key marks terminal state; Python string iteration never supplies None as a character.
Its Boolean value is not another child dictionary.
Problem trace
The same node can be a valid prefix without ending a word
double border complete word
- edges
- [root -> a, a -> ap, ap -> app, app -> appl, appl -> apple]
- operation
- insert("app")
- existing
- root only
double border complete word
- path
- not shown→root -a-> a
- operation
- insert("app")→not shown
- existing
- root only→not shown
double border complete word
- path
- root -a-> a→root -a-> a -p-> ap
double border complete word
- path
- root -a-> a -p-> ap→root -a-> a -p-> ap -p-> app
- terminal
- not shown→app=yes
double border complete word
- operation
- not shown→insert("apple")
- created
- not shown→appl, apple
- path
- root -a-> a -p-> ap -p-> app→not shown
double border complete word
- query
- not shown→search("ap")
- outcome
- not shown→false
- operation
- insert("apple")→not shown
double border complete word
- query
- search("ap")→starts_with("ap")
- outcome
- false→true
double border complete word
- query
- starts_with("ap")→search("app")
- result
- not shown→true
- outcome
- true→not shown
- Recognize it
- Many words share prefixes and queries distinguish prefix existence from complete-word membership.
- Keep true
- The root-to-node edge labels spell its prefix; terminal is true exactly for inserted complete words.
- Reuse it
- Store shared prefixes once and attach terminal or payload state to nodes.
Reference drawing
Problem trace
The same node can be a valid prefix without ending a word
Execution trace
double border complete word
- edges
- [root -> a, a -> ap, ap -> app, app -> appl, appl -> apple]
- operation
- insert("app")
- existing
- root only
double border complete word
- path
- not shown→root -a-> a
- operation
- insert("app")→not shown
- existing
- root only→not shown
double border complete word
- path
- root -a-> a→root -a-> a -p-> ap
double border complete word
- path
- root -a-> a -p-> ap→root -a-> a -p-> ap -p-> app
- terminal
- not shown→app=yes
double border complete word
- operation
- not shown→insert("apple")
- created
- not shown→appl, apple
- path
- root -a-> a -p-> ap -p-> app→not shown
double border complete word
- query
- not shown→search("ap")
- outcome
- not shown→false
- operation
- insert("apple")→not shown
double border complete word
- query
- search("ap")→starts_with("ap")
- outcome
- false→true
double border complete word
- query
- starts_with("ap")→search("app")
- result
- not shown→true
- outcome
- true→not shown
- Recognize it
- Many words share prefixes and queries distinguish prefix existence from complete-word membership.
- Keep true
- The root-to-node edge labels spell its prefix; terminal is true exactly for inserted complete words.
- Reuse it
- Store shared prefixes once and attach terminal or payload state to nodes.
Code
class Trie:
def __init__(self) -> None:
self.root: dict = {}
def insert(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault(char, {})
node[None] = True
def _walk(self, text: str) -> dict | None:
node = self.root
for char in text:
if char not in node:
return None
node = node[char]
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and None in node
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not None
For query characters, map-based operations take expected work under ordinary hashing assumptions. Stored space is proportional to distinct prefix nodes and terminal markers, not repeated copies of shared words. Repeated insertion is idempotent.
The empty prefix exists even before insertion; the empty word exists only after inserting "".
Testing node is not None preserves the distinction between a missing path and an existing empty dictionary.
Failure Check
Returning success after _walk("ap") without checking terminal state would confuse prefixes with complete words.
Using an input character as the terminal sentinel would create a collision with valid data.
Change to Membership Deletion
New task: Remove app without removing apple.
Picture and change: Remove only the terminal key at the reached node; retain its children. This complete example builds a trie and returns deletion success plus the requested word-membership results.
def trie_delete_case(words, removed_word, queries):
trie = Trie()
for word in words:
trie.insert(word)
node = trie._walk(removed_word)
removed = node is not None and None in node
if removed:
del node[None]
return [removed, [trie.search(query) for query in queries]]
Check: trie_delete_case(["app","apple"], "app", ["app","apple"]) returns [True,[False,True]].
Deleting a terminal does not reclaim unused paths.
Even after deleting the only word, storage-level prefix search can still find its orphaned path.
Use when: Removing membership suffices; live-word prefix semantics or reclamation needs additional bookkeeping.
Change to Prefix Completions
New task: Return all stored words extending a prefix, in Python string order.
Picture and change: Walk to the prefix, emit terminal nodes, and traverse character children while excluding None.
def trie_completions(words, prefix):
trie = Trie()
for word in words:
trie.insert(word)
node = trie._walk(prefix)
result = []
def visit(current, text):
if None in current:
result.append(text)
for char in sorted(key for key in current if key is not None):
visit(current[char], text + char)
if node is not None:
visit(node, prefix)
return result
Check: Words ["apple","app","app","apt"] and prefix "ap" return ["app","apple","apt"].
Duplicates emit once; the empty word can appear when querying the empty prefix.
Cost includes construction, visited descendants, child sorting and string copies, not just prefix length.
Concatenation can copy quadratically along one long chain; deep recursion can exceed Python’s limit.
Use when: The query needs word witnesses, not a Boolean path answer.
Transfer Check
What changes when a query contains a wildcard?
Answer
Explore multiple character children at that position, but still require terminal state at the query’s end.