Word Dictionary with Insert and Query Operations
Data Structure DesignAuto-graded · 20 test casesLast updated
Tests implementing a character-level trie to handle insert, exact-match lookup, and prefix-existence queries while distinguishing complete words from prefixes.
Implement a dictionary for lowercase English words that handles three types of operations in sequence:
["insert", w]: store wordwin the dictionary["search", w]: check whether wordwexists in the dictionary["prefix", p]: check whether any stored word begins with stringp
Given a list of operations, execute them in order and return a list of boolean results for every search and prefix query, preserving their original order.
Rules
- The dictionary begins empty.
- Each operation is a two-string list: the command type followed by a word or prefix string.
insertcommands produce no output. Re-inserting a word that already exists has no effect.searchreturns true only when the exact word was previously inserted; a string that is merely a prefix of a stored word returns false.prefixreturns true when at least one stored word starts with the given string, including the case where a stored word exactly equals the prefix string.- Each query reflects only the words inserted before that query.
- If no
searchorprefixoperations appear, return an empty list.
Constraints
1 ≤ len(operations) ≤ 2 × 10⁴- Each operation type is one of
"insert","search", or"prefix" - Each word and prefix string has length in
[1, 100]and contains only lowercase lettersa–z
Examples
Example 1
Input: process_word_dictionary([['insert', 'card'], ['search', 'car'], ['prefix', 'car'], ['insert', 'car'], ['search', 'car'], ['search', 'cards']])
Output: [False, True, True, False]
Example 2
Input: process_word_dictionary([['prefix', 'a'], ['insert', 'a'], ['prefix', 'a'], ['search', 'a'], ['search', 'ab']])
Output: [False, True, True, False]
Example 3
Input: process_word_dictionary([['insert', 'x']])
Output: []
Hints
Hint 1
A trie (prefix tree) naturally separates the concept of 'a path exists' from 'a word ends here'.
Hint 2
Mark the final node of each inserted word with a special flag to distinguish complete words from intermediate prefixes.
Hint 3
Both search and prefix queries walk the same path character by character; they differ only in what they check at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A trie (prefix tree) is the natural data structure for this problem. Each node in the trie represents a character position, with edges labeled by characters leading to child nodes. Words sharing a common prefix share the same path from the root.
The key insight is maintaining two pieces of information:
- Path existence: whether a sequence of characters forms a valid path in the trie
- Word completion: whether that path corresponds to a complete inserted word
We mark word endings with a special sentinel key (such as '$') that cannot collide with any actual character. This marker distinguishes between a word that was inserted and a string that merely happens to be a prefix of some longer word.
For insert operations, we traverse character by character from the root, creating nodes as needed, then place the end-marker at the final node. For queries, we walk the same path; prefix queries succeed if the path exists, while search queries additionally require the end-marker to be present.
Correctness
The trie maintains this invariant: a path from the root exists if and only if some inserted word contains that prefix. The end-marker appears at a node if and only if the word formed by the path to that node was inserted.
Processing operations sequentially ensures each query sees exactly the words inserted before it. Re-inserting a word sets the marker again, which is idempotent and produces no change.
Complexity
- Time: O(S) where S is the total number of characters across all operations. Each operation processes its word or prefix once, performing O(length) dictionary operations.
- Space: O(T) where T is the total characters in all distinct inserted words. Shared prefixes are stored once, which is the main advantage over storing words in a hash set.
Solution
from typing import List
def process_word_dictionary(operations: List[List[str]]) -> List[bool]:
trie_root = {}
WORD_END = '$'
results = []
for command, text in operations:
if command == 'insert':
current = trie_root
for char in text:
if char not in current:
current[char] = {}
current = current[char]
current[WORD_END] = True
else:
current = trie_root
path_exists = True
for char in text:
if char in current:
current = current[char]
else:
path_exists = False
break
if command == 'search':
results.append(path_exists and WORD_END in current)
else: # command == 'prefix'
results.append(path_exists)
return results