Skip to content
mlmentorship

Share prefix paths and mark complete words separately

Trace character edges, distinguish membership from prefix reachability, then delete terminal state or enumerate completions.

Published · 15 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Share prefix paths and mark complete words separately

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each root-to-node path is one shared prefix; terminal state distinguishes a complete word from a mere prefix.

Problem trace

The same node can be a valid prefix without ending a word

Worked example: prefix reachability and word membership are separate flagsAfter inserting apple, app is a valid prefix but not yet a word. Inserting app changes its terminal flag without rebuilding the shared path.A reachable prefix path and astored-word flag are separate stateAfter apple only: app is not yet awordappleapp: prefixapple:wordInsert app: keep the path; add itsword flagappleapp: wordapple:word
Read it this way: After inserting apple, app is a valid prefix but not yet a word. Inserting app changes its terminal flag without rebuilding the shared path. Does inserting app require replacing the existing apple path or deleting its terminal flag?
Full interview answer 15 min read

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

Input and goalSupport word insert, full-word search, and prefix search.
Start with an empty rootThe root has no child before insert("app").
Shared-prefix trieOne node per shared prefix; double borders mark complete words.currentroot

double border complete word

operationinsert("app")existingroot only
edges
[root -> a, a -> ap, ap -> app, app -> appl, appl -> apple]
operation
insert("app")
existing
root only

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.
The root has no child before insert("app"). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does starts_with(ap) succeed while search(ap) fails at the very same node?
Reference drawing

Problem trace

The same node can be a valid prefix without ending a word

Worked example: prefix reachability and word membership are separate flagsAfter inserting apple, app is a valid prefix but not yet a word. Inserting app changes its terminal flag without rebuilding the shared path.A reachable prefix path and astored-word flag are separate stateAfter apple only: app is not yet awordappleapp: prefixapple:wordInsert app: keep the path; add itsword flagappleapp: wordapple:word
Execution trace
Input and goalSupport word insert, full-word search, and prefix search.
Start with an empty rootThe root has no child before insert("app").
Shared-prefix trieOne node per shared prefix; double borders mark complete words.currentroot

double border complete word

operationinsert("app")existingroot only
edges
[root -> a, a -> ap, ap -> app, app -> appl, appl -> apple]
operation
insert("app")
existing
root only

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.
The root has no child before insert("app"). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does starts_with(ap) succeed while search(ap) fails at the very same node?
Read it this way: After inserting apple, app is a valid prefix but not yet a word. Inserting app changes its terminal flag without rebuilding the shared path. Does inserting app require replacing the existing apple path or deleting its terminal flag?

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.