Sequential Word Dictionary With Exact and Prefix Lookups
Medium · Coding & Algorithms · Software Engineer · Other
Problem Statement
Implement an in-memory dictionary for lowercase English strings that executes a stream of commands sequentially. Every command in operations is a two-string pair [command, arg]:
["insert", word]: storeswordin the dictionary and emits no boolean output. Re-adding a string that was already stored leaves the dictionary unchanged.["search", word]: evaluates toTrueifwordwas previously stored as a complete entry, orFalseotherwise (matching only the beginning of a longer stored entry returnsFalse).["prefix", pref]: evaluates toTrueif at least one previously stored entry begins withpref(an entry equal toprefcounts as beginning withpref), orFalseotherwise.
The dictionary begins empty, and every lookup observes only entries added prior to that lookup. Return a list containing the boolean results of all "search" and "prefix" commands in their arrival order (or [] when the stream contains only insertions).
def run_word_index(operations: List[List[str]]) -> List[bool]:
Examples
Example 1
Input: operations = [
["insert", "planet"],
["prefix", "plan"],
["search", "plan"],
["insert", "plan"],
["search", "plan"],
["prefix", "plaza"]
]
Output: [True, False, True, False]
Explanation: After storing "planet", "plan" matches as a prefix (True) yet fails exact lookup (False) because "plan" itself has not been added yet. Once "plan" is inserted, exact lookup for "plan" becomes True, while "plaza" diverges at 'z' and returns False.
Example 2
Input: operations = [
["search", "go"],
["insert", "go"],
["insert", "go"],
["prefix", "go"],
["prefix", "goal"],
["search", "go"]
]
Output: [False, True, False, True]
Explanation: Looking up "go" before any insertion yields False. Storing "go" twice behaves identically to storing it once: "go" matches as a prefix of itself (True), "goal" extends past "go" (False), and exact lookup for "go" succeeds (True).
Example 3
Input: operations = [["insert", "mint"], ["insert", "mine"]]
Output: []
Explanation: Neither command is a lookup, so the returned result list is empty.
Constraints
1 <= len(operations) <= 2 * 10^4- For each
[command, arg],commandis"insert","search", or"prefix". 1 <= len(arg) <= 100, consisting solely of lowercase ASCII letters ('a'through'z').
Step-by-step walkthrough
Understand the three operations
We begin with an empty dictionary and replay a list of
[op_name, text]commands sequentially (1 <= len(operations) <= 2 * 10^4, wheretexthas1..100lowercase lettersa..z):["insert", w]: recordwin the dictionary (emits no boolean; re-inserting an existing word has no effect).["search", w]: returnTrueonly whenwitself was previously stored as a whole word.["prefix", p]: returnTruewhenever at least one previously stored word starts withp(including a stored word equal top).
Watch the distinction between
"search"and"prefix":After only ["insert", "planet"]: ["prefix", "plan"] -> True ("planet" begins with "plan") ["search", "plan"] -> False ("plan" itself was not stored yet) ["prefix", "planet"] -> True ("planet" begins with "planet")Why scanning a plain word list is slow for prefixes
If we store every inserted word in a Python
set:["search", w]isw in words, which runs in O(len(w)) average time — already fast.["prefix", p], however, cannot use a single hash lookup onwords: we would have to scan every stored word and checkword.startswith(p).
With
10,000inserted words of length100followed by10,000prefix lookups, scanning every word per query performs up to10,000 * 10,000 = 10^8startswithchecks. We want"prefix"to take only O(len(p)) steps, independent of how many words are stored!Key idea: share common beginnings in a tree of letters (a trie)
A trie (also called a prefix tree) organizes words character by character from a shared
rootnode. Words that begin with the same letters share the exact same chain of nodes before branching apart:After inserting "planet", "plan", and "play" (* marks is_word = True): (root) | [p] | [l] | [a] / \ [n]* [y]* | [e] | [t]*Look at what that structure gives us automatically:
- Every node was created while inserting some word. Therefore at least one stored word starts with
pif and only if walking the letters ofpfromrootnever hits a missing link. - A prefix node is not automatically a whole word. Before
"plan"was inserted,[n]already existed along the path to[t]*, so we keep a boolean flagis_wordon each node to mark where complete words finish.
- Every node was created while inserting some word. Therefore at least one stored word starts with
Build `TrieNode` and `insert`
Each
TrieNodestores two attributes:children: a dictionary mapping a single letter (such as'a') to the nextTrieNode.is_word:Falseinitially, set toTrueon the node where an inserted word ends.
To insert
word, start atself.root, step through each letter (allocating a newTrieNodewhenever a letter link is missing), and marknode.is_word = Trueat the final node. Inserting the same word twice walks the existing path and setsis_word = Trueagain, so duplicates harmlessly do nothing.class TrieNode: def __init__(self) -> None: # children: maps single letter -> child TrieNode, e.g. {'a': TrieNode(), 'b': TrieNode()}. self.children: Dict[str, "TrieNode"] = {} # is_word: True only when at least one inserted word ends at this exact node. self.is_word: bool = False class Trie: def __init__(self) -> None: # The root represents the empty prefix "" before any letters are read. self.root = TrieNode() def insert(self, word: str) -> None: # Walk letter by letter from the root, creating missing child nodes as needed. node = self.root for letter in word: if letter not in node.children: node.children[letter] = TrieNode() node = node.children[letter] # Mark the final letter's node as a complete word (duplicate inserts keep it True). node.is_word = TrueShare one read-only walk for `search` and `starts_with`
Both
"search"and"prefix"walk down fromself.rootletter by letter without modifying the tree. Let's place that shared traversal in a helper_find_node(text)that returns the reachedTrieNode(orNoneas soon as a letter is missing):search(word)returnsTruewhennode is not None and node.is_word.starts_with(prefix)returnsTruewhennode is not None.
Be careful never to create missing nodes inside
_find_node(for instance withdefaultdict): lookups must leave the trie completely unchanged!def _find_node(self, text: str) -> Optional[TrieNode]: """Follow `text` from the root without modifying the trie, or return None if broken.""" node = self.root for letter in text: if letter not in node.children: return None node = node.children[letter] return node def search(self, word: str) -> bool: # Exact match requires the full path to exist AND an inserted word to end here. node = self._find_node(word) return node is not None and node.is_word def starts_with(self, prefix: str) -> bool: # Every node in the trie was created along some inserted word, so path existence suffices. node = self._find_node(prefix) return node is not NoneReplay operations and trace Example 1
Finally,
run_word_indexcreates an emptyTrie, iterates overoperationsin order, and appends boolean results only for"search"and"prefix".Let's trace Example 1:
Operation Trie state (* = is_word) Walk result Output appended --------------------- ------------------------------------ -------------------------- --------------- ["insert", "planet"] root->p->l->a->n->e->t* marks t.is_word = True (none) ["prefix", "plan"] root->p->l->a->n->e->t* reaches n (not None) True ["search", "plan"] root->p->l->a->n->e->t* reaches n, n.is_word=False False ["insert", "plan"] root->p->l->a->n*->e->t* marks n.is_word = True (none) ["search", "plan"] root->p->l->a->n*->e->t* reaches n*, n.is_word=True True ["prefix", "plaza"] root->p->l->a->n*->e->t* a has no child 'z' -> None FalseCollected
answers:[True, False, True, False].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class TrieNode: def __init__(self) -> None: # children: maps single letter -> child TrieNode, e.g. {'a': TrieNode(), 'b': TrieNode()}. self.children: Dict[str, "TrieNode"] = {} # is_word: True only when at least one inserted word ends at this exact node. self.is_word: bool = False class Trie: def __init__(self) -> None: # The root represents the empty prefix "" before any letters are read. self.root = TrieNode() def insert(self, word: str) -> None: # Walk letter by letter from the root, creating missing child nodes as needed. node = self.root for letter in word: if letter not in node.children: node.children[letter] = TrieNode() node = node.children[letter] # Mark the final letter's node as a complete word (duplicate inserts keep it True). node.is_word = True def _find_node(self, text: str) -> Optional[TrieNode]: """Follow `text` from the root without modifying the trie, or return None if broken.""" node = self.root for letter in text: if letter not in node.children: return None node = node.children[letter] return node def search(self, word: str) -> bool: # Exact match requires the full path to exist AND an inserted word to end here. node = self._find_node(word) return node is not None and node.is_word def starts_with(self, prefix: str) -> bool: # Every node in the trie was created along some inserted word, so path existence suffices. node = self._find_node(prefix) return node is not None def run_word_index(operations: List[List[str]]) -> List[bool]: trie = Trie() # answers: collects boolean results ONLY for "search" and "prefix" queries in order. answers: List[bool] = [] for op_name, text in operations: if op_name == "insert": trie.insert(text) elif op_name == "search": answers.append(trie.search(text)) elif op_name == "prefix": answers.append(trie.starts_with(text)) else: raise ValueError(f"unknown operation: {op_name}") return answers✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing words as a tree of road signs where each step follows a single letter from an entrance plaza (root). When you add "planet", you build a six-step path p -> l -> a -> n -> e -> t and stick a star (is_word = True) on t to mark that a complete word finishes there. Any word starting with "plan" — such as "plan", "planet", or "plank" — shares the exact same p -> l -> a -> n beginning! This structure is called a trie (or prefix tree, a tree where each edge is labeled with one character so shared word beginnings share nodes). Checking "prefix" just walks the letters and asks "did the road exist?", while checking "search" walks the same letters and also asks "does this signpost have a star?".
A naive implementation that keeps stored words in a hash set (an unordered collection supporting O(1) average exact-key lookup) handles "search" quickly, because exact lookup is what hash sets are built for. However, hash sets scramble keys by their full string hash, so answering ["prefix", p] forces you to scan every stored word and test word.startswith(p). With 10,000 inserts followed by 10,000 prefix queries, scanning every word takes up to 100 million startswith checks, whereas a trie walks at most len(p) <= 100 nodes per query regardless of how many words are stored.
Walk through Example 1 ([["insert", "planet"], ["prefix", "plan"], ["search", "plan"], ["insert", "plan"], ["search", "plan"], ["prefix", "plaza"]]):
insert "planet": createsroot -> p -> l -> a -> n -> e -> tand markst.is_word = True(no output).prefix "plan": walks ton, seesnexists (not None), appendsTrue.search "plan": walks ton, seesn.is_wordisFalse, appendsFalse.insert "plan": walks existingroot -> p -> l -> a -> nand flipsn.is_word = True(no output).search "plan": walks ton, seesn.is_wordis nowTrue, appendsTrue.prefix "plaza": hitsNoneat'z'under'a', appendsFalse->[True, False, True, False].
Complexity
Let L be the length of the word or prefix in a single operation (L <= 100), S be the sum of L across all operations (at most 2 * 10^4 * 100 = 2 * 10^6), and I be the total characters across all "insert" operations.
- Time: O(L) per operation, and O(S) overall. Each
"insert","search", or"prefix"call steps through at mostLcharacters, doing one O(1) average-time dictionary lookup (and at most one O(1) insertion during"insert") per character. - Space: O(I + Q), where Q is the number of queries. In the worst case where stored words share almost no prefixes,
"insert"allocates at most oneTrieNodeper inserted character (O(I)nodes, often far fewer when prefixes overlap), andanswersstores one boolean for each of theQlookups.
Edge cases
- Lookups on an empty dictionary:
self.root.childrenis empty, so_find_nodeimmediately returnsNoneon the first character (L >= 1) and both"search"and"prefix"returnFalse. - Prefix that is not yet a whole word: after
insert "planet",search "plan"returnsFalsewhileprefix "plan"returnsTrue. - Prefix equal to a stored word: after
insert "go",prefix "go"reacheso(not None) and returnsTrue(Example 2). - Query longer than any stored word: after
insert "go",prefix "goal"hitsNoneat'a'and returnsFalse. - Duplicate inserts: inserting
"go"twice walks the same path and leaveso.is_word = Trueunchanged. - Only
"insert"operations:answersstays empty and returns[](Example 3). - Separate branches with the same letters: inserting
"ab"and"ba"creates independent pathsroot -> a -> bandroot -> b -> a, never falsely matching"aa"or"bb".
Common mistakes
- Omitting
is_word: checking only whether the path exists makessearch "plan"wrongly returnTrueafter inserting"planet". - Mutating the trie during lookups: using
collections.defaultdict(TrieNode)and indexingnode.children[letter]insidesearchorstarts_withsilently inserts phantom nodes, causing future"prefix"lookups on unstored strings to returnTrue. - Defining
children = {}as a class attribute instead of inside__init__: causes everyTrieNodein the entire tree to share one single dictionary! - Appending
NoneorTruefor"insert": the output list must contain answers only for"search"and"prefix"commands. - Scanning a list of all words on every
"prefix"call: takes O(number of words * L) per lookup instead of O(L).
Alternative approaches
- Two hash sets (
wordsandprefixes): oninsert(w), addwtowordsand add every slicew[:1], w[:2], ..., w[:L]toprefixes, turning both"search"and"prefix"into O(L) hash lookups. However, slicing and hashing every prefix takes O(L^2) character copies per insert (about 5,050 characters per 100-letter word) instead of O(L), and does not naturally extend to autocomplete or deletion. - Sorted word list with binary search (
bisect_left): keep distinct inserted words in alphabetical order; some word starts withpif and only if the first stored word>= p(found in O(log N) comparisons via binary search, repeatedly halving the sorted list) starts withp. Queries are fast, but inserting into the middle of a Pythonlistshifts elements in O(N) time per insert.
Follow-up questions
- How would you extend the trie to report how many distinct stored words begin with a given prefix? Add an integer
prefix_count = 0to everyTrieNode. Before insertingword, checkif self.search(word): returnso duplicate inserts are ignored; otherwise walk fromrootthroughwordand incrementnode.prefix_count += 1at every node along the path. Answering a prefix-count lookup then runs_find_node(p)in O(len(p)) time and returnsnode.prefix_count(or0whennode is None). - How would you implement word deletion without leaving stale paths that break future prefix checks? First confirm
wis stored in the trie; if so, clearend_node.is_word = Falseat the end ofw's path. You must also prune dead branches on the way back up—deleting any child node whoseis_wordisFalseand whosechildrendict is now empty—otherwisestarts_withwould still see leftover nodes from the deleted word and returnTrue. Alternatively, maintainprefix_counton every node, decrement it alongw's path on deletion, and treat any node withprefix_count == 0as absent. - How would you return the top k autocomplete suggestions for a typed prefix? Call
_find_node(p)to jump directly top's subtree in O(len(p)) time; ifNone, return[]. To return thekalphabetically smallest completions, run a depth-first search (exploring one letter branch to its end before backtracking to the next) from that node visiting child letters from'a'to'z'and stop as soon as you collectknodes withis_word == True. If completions are ranked by popularity instead, precompute and cache each node's top-khighest-scoring words duringinsertso queries return in O(len(p) + k) time without traversing the full subtree.
Follow-up questions
- How would you extend the trie to report how many distinct stored words begin with a given prefix?
- How would you implement word deletion without leaving stale paths that break future prefix checks?
- How would you return the top k autocomplete suggestions for a typed prefix?
Similar questions
- Presenting Your Proudest Engineering Project
- Rail Seat Reservation Service
- Architecting a High-Throughput URL Shortener
- Spring Boot 3 Internals and Modern Java 21 Deep Dive
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger