Word Index with Prefix Queries and Ordered Suggestions
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a command sequence on a word index that supports insert, exact lookup, prefix lookup, and alphabetically ordered, capped autocomplete, built on a trie.
Word Index Simulator
You are building a small in-memory word index. It begins empty and then processes a list of commands in order. Implement run_word_index(commands, params), which executes every command against one shared index and returns the result of each command.
Commands
commands[i] is the name of the i-th command, and params[i] is the list of arguments for it.
| Command | Arguments | Effect | Result recorded |
|---|---|---|---|
"insert" | [word] | Add word to the index. Inserting a word that is already present changes nothing. | None |
"has_word" | [word] | Check whether word was inserted exactly as given. | True or False |
"has_prefix" | [prefix] | Check whether at least one stored word starts with prefix. | True or False |
"autocomplete" | [prefix, limit] | Collect stored words that start with prefix. | A list of strings |
Autocomplete rules
- A word counts as starting with
prefixifprefixis the word itself or a leading part of it. So a stored word equal toprefixis a match. - Return the matching words in ascending dictionary (lexicographic) order. A word comes before every longer word that extends it.
- Return at most
limitwords, taking the smallest ones in that order. If fewer words match, return all of them. - Each distinct word appears at most once, no matter how many times it was inserted.
- If nothing matches, or
limitis0, return an empty list.
Empty prefix
An empty prefix "" is allowed in has_prefix and autocomplete. It is a leading part of every word, so autocomplete("", k) lists the smallest k stored words. On an index with no words, has_prefix("") is still True and autocomplete("", k) returns []. A has_word("") query is True only if the empty string was itself inserted.
Output
Return a list with one entry per command, in the same order as commands. The entry is the result from the table above.
Constraints
len(commands) == len(params), and every command name is one of the four listed above.- The total number of commands is at most
2 * 10^4. - Every
wordandprefixhas length between0and100and contains only lowercase letters'a'to'z'. 0 <= limit <= 100.
Examples
Example 1
Input: run_word_index(['insert', 'insert', 'insert', 'insert', 'insert', 'has_word', 'has_word', 'has_prefix', 'has_prefix', 'autocomplete', 'autocomplete', 'autocomplete'], [['apple'], ['app'], ['application'], ['apt'], ['banana'], ['app'], ['appl'], ['appl'], ['bat'], ['app', 2], ['app', 5], ['z', 3]])
Output: [None, None, None, None, None, True, False, True, False, ['app', 'apple'], ['app', 'apple', 'application'], []]
Example 2
Input: run_word_index(['insert', 'insert', 'insert', 'insert', 'has_word', 'has_word', 'has_prefix', 'autocomplete', 'autocomplete', 'autocomplete'], [['car'], ['cart'], ['cat'], ['car'], ['ca'], ['cart'], ['car'], ['ca', 10], ['car', 1], ['cat', 0]])
Output: [None, None, None, None, False, True, True, ['car', 'cart', 'cat'], ['car'], []]
Example 3
Input: run_word_index(['has_word', 'has_prefix', 'autocomplete', 'insert', 'has_word', 'has_prefix', 'autocomplete'], [['a'], [''], ['', 5], ['a'], ['a'], [''], ['', 10]])
Output: [False, True, [], None, True, True, ['a']]
Hints
Hint 1
Store words in a tree where each edge is one letter and each node records whether a stored word ends there. Exact lookup and prefix lookup then differ only in that final flag.
Hint 2
Write one helper that walks a string from the root and returns the node reached, or nothing if the path breaks. All three query types can use it.
Hint 3
For autocomplete, run a DFS from the prefix node. Report a node's own word before descending, and visit children in alphabetical order. That visiting order is already sorted, so stop as soon as you have `limit` words.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the words in a trie. Each node stands for a string prefix, its children extend that prefix by one letter, and a boolean terminal flag marks nodes where an inserted word ends.
- insert: walk from the root, creating missing child nodes, and set
terminalon the last node. Inserting the same word again just sets the flag again, so there are no duplicates. - Path walk helper: follow the characters of a string from the root and return the node reached, or
Noneif some letter has no child. - has_word: the walk succeeds and the final node is
terminal. - has_prefix: the walk succeeds. Nodes are only created by inserts and never removed, so every existing node lies on the path of some stored word. The empty prefix reaches the root, so it always succeeds.
- autocomplete: return
[]iflimitis0or the walk fails. Otherwise run a DFS from the prefix node. At each node, first emit its own word if it isterminal, then visit children in alphabetical order. Stop oncelimitwords are collected.
Why it is correct
The DFS emits a node before its descendants, so a word always comes before any longer word that extends it. Among different branches, the smaller letter is fully explored first. For any two matching words, the one that is smaller in dictionary order is therefore emitted first. The traversal produces matches already sorted, so stopping after limit words yields exactly the limit smallest ones, with no sorting of results needed. Each word corresponds to exactly one node, so no word is returned twice. A limit of 0 is handled before any traversal, and a missing path gives an empty list. The empty prefix starts the DFS at the root, which lists the smallest words overall.
Complexity
Let L be the length of a word or prefix, M the maximum word length, and k the limit.
insert,has_word,has_prefix: O(L) time each.autocomplete: O(L + k·M·26) time in the worst case. The early stop means the whole subtree is never explored, and each emitted word adds at most aboutMnewly visited nodes.- Space: O(total inserted characters) for the trie, plus O(M) recursion depth and O(k·M) for the output.
Reference solution
from typing import List
class _Node:
def __init__(self):
self.children = {}
self.terminal = False
class _WordIndex:
def __init__(self):
self.root = _Node()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = _Node()
node = node.children[ch]
node.terminal = True
def _walk(self, text):
node = self.root
for ch in text:
if ch not in node.children:
return None
node = node.children[ch]
return node
def has_word(self, word):
node = self._walk(word)
return node is not None and node.terminal
def has_prefix(self, prefix):
return self._walk(prefix) is not None
def autocomplete(self, prefix, limit):
if limit <= 0:
return []
start = self._walk(prefix)
if start is None:
return []
out = []
path = list(prefix)
def dfs(node):
if len(out) >= limit:
return
if node.terminal:
out.append("".join(path))
for ch in sorted(node.children):
if len(out) >= limit:
return
path.append(ch)
dfs(node.children[ch])
path.pop()
dfs(start)
return out
def run_word_index(commands: List[str], params: List[List[object]]) -> List[object]:
index = _WordIndex()
results = []
for cmd, args in zip(commands, params):
if cmd == "insert":
index.insert(args[0])
results.append(None)
elif cmd == "has_word":
results.append(index.has_word(args[0]))
elif cmd == "has_prefix":
results.append(index.has_prefix(args[0]))
elif cmd == "autocomplete":
results.append(index.autocomplete(args[0], args[1]))
return results