Weighted Prefix Suggestion Engine via Command Replay
Data Structure DesignAuto-graded · 19 test casesLast updated
Replay a list of add and search commands on a weighted word store, returning the top-k prefix matches ranked by weight, then alphabetically.
Weighted Prefix Suggestions
You are building the core of a search-suggestion feature. It keeps a collection of words, each with an integer score, and answers prefix queries by returning the best-scoring matches.
Instead of writing a class, you implement a single function that replays a list of commands against an initially empty collection and reports what each command produced.
Commands
Command i is named by commands[i] and its arguments are in params[i].
-
"add_word"withparams[i] = [word, weight]- Stores
wordwith the given integerweight. - If
wordis already stored, its weight is replaced by the new value. The weights are not summed, and no duplicate entry is created. The new weight may be lower or higher than the old one. - Produces
Nonein the output.
- Stores
-
"search"withparams[i] = [prefix, k]- Considers every stored word that starts with
prefix. A word counts as starting with itself, and the empty prefix""matches every stored word. - Returns at most
kof those words, ranked by:- weight, highest first;
- then, among equal weights, ordinary lexicographic (string) order, smallest first.
- If fewer than
kwords match, return all of them in that order. - If nothing matches, return an empty list.
- Searching never modifies the collection.
- Considers every stored word that starts with
Output
Return a list with one entry per command, in the same order. The entry is None for "add_word", and the list of suggested words for "search".
Each search must reflect all add_word commands that came before it, and only those.
Constraints
len(commands) == len(params).- Every command name is either
"add_word"or"search". - Words and prefixes consist of strings of characters. Prefixes may be empty, and words are non-empty.
- Weights are integers (they may be negative or zero).
kis a positive integer with no fixed upper bound, so it may exceed the number of matches.- The total number of characters across all added words is at most 10^6.
Examples
Example 1
Input: run_suggestion_commands(['add_word', 'add_word', 'add_word', 'add_word', 'search'], [['apple', 10], ['apply', 15], ['app', 5], ['bat', 20], ['app', 2]])
Output: [None, None, None, None, ['apply', 'apple']]
Hints
Hint 1
A trie is a natural fit for prefix matching: following the prefix character by character leads to a node whose subtree is exactly the set of matching words.
Hint 2
Keep the words and their weights in separate places: the trie decides which words match, and a dictionary from word to current weight decides how they rank. This makes re-adding a word with a lower weight trivial.
Hint 3
Rank matches with the sort key (-weight, word). When only k results are needed, heapq.nsmallest with that key avoids sorting everything.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Prefix lookups are what a trie does well, but the ranking rule and the possibility of weights being lowered make per-node cached top-k lists fragile. Also, k has no upper bound, so a cache of fixed size cannot answer every query. So the design separates two concerns:
- Membership (which words match a prefix): each trie node keeps a set of all complete words in its subtree, including a word that ends at that node. The root's set holds every word.
- Ranking (how matches are ordered): one dictionary maps each word to its current weight.
Processing the commands in order:
add_word: if the word is new, walk its characters, creating nodes as needed, and add the word to the set of every node on the path (root included). Then store the weight in the dictionary. If the word already exists, membership is unchanged, so only the dictionary entry is overwritten. This handles both increases and decreases with no extra work.search: walk the prefix from the root. If a character is missing, the answer is[]. Otherwise take the node's word set and select theksmallest under the key(-weight, word), usingheapq.nsmallest. That key sorts by weight descending and then lexicographically ascending, exactly as specified. If there are fewer thankmatches, all of them are returned in order.
Why it is correct
- A word is in the set of the node reached by
prefixif and only if the word passed through that node when inserted, which happens exactly whenprefixis a prefix of the word (including the word itself and the empty prefix at the root). - Ranking reads the live weight dictionary at query time, so a replaced weight can never leave stale information behind.
- Words are never added twice, because the sets and the "already exists" check prevent duplicates.
nsmallestwith a total-order key returns the firstkitems in sorted order, which is the required result.
Complexity
Let L be the length of an added word, P the length of the prefix, and m the number of words matching a search.
add_word: O(L) time for a new word, and O(L) for an existing word (hashing the string).search: O(P + m log k) time.- Space: O(total characters), since each word is stored in L + 1 node sets (about 2·10^6 references at most) plus the trie nodes.
Reference solution
import heapq
from typing import List, Optional
class _Node:
__slots__ = ("children", "words")
def __init__(self):
self.children = {}
self.words = set()
def run_suggestion_commands(commands: List[str], params: List[List]) -> List[Optional[List[str]]]:
root = _Node()
weight_of = {}
output = []
for command, args in zip(commands, params):
if command == "add_word":
word, weight = args
if word not in weight_of:
node = root
node.words.add(word)
for ch in word:
nxt = node.children.get(ch)
if nxt is None:
nxt = _Node()
node.children[ch] = nxt
node = nxt
node.words.add(word)
weight_of[word] = weight
output.append(None)
elif command == "search":
prefix, k = args
node = root
for ch in prefix:
node = node.children.get(ch)
if node is None:
break
if node is None:
output.append([])
else:
best = heapq.nsmallest(k, node.words, key=lambda w: (-weight_of[w], w))
output.append(best)
else:
raise ValueError("unknown command")
return output