Ad platform~25 min2s · 256 MBtarget O(total length) time, O(total length) spacetrie
An ad-planning tool suggests a keyword while an advertiser types. It keeps an index of words, and each word has a weight: the number of times advertisers chose it. Weights grow while the tool runs, and suggestions must always use the latest totals.
For the letters typed so far, the tool suggests the word with the highest weight among the words that start with them. If two words have the same weight, it suggests the one that comes first in the alphabet.
Write run_index(commands, words, weights).
commands[i] is "add" or "suggest"."add" has words[i] as the word and weights[i] (at least 1) as its weight. It adds the weight to the total of that word. A new word starts at 0."suggest" has words[i] as the prefix and weights[i] = 0. Return the word that starts with the prefix and has the largest total weight, the smaller word on a tie. Return "-" when no word starts with the prefix."suggest" commands, in order.Input: commands = ["add", "add", "add", "suggest", "add", "suggest", "suggest", "suggest"], words = ["tea", "ten", "tea", "te", "ten", "te", "tex", "x"], weights = [5, 8, 4, 0, 3, 0, 0, 0]
Output: ["tea", "ten", "-", "-"]The table shows what each command does.
| Step | Command | Totals of the words under "te" | Output |
|---|---|---|---|
| 1 | add tea 5 | tea 5 | |
| 2 | add ten 8 | tea 5, ten 8 | |
| 3 | add tea 4 | tea 9, ten 8 | |
| 4 | suggest te | tea 9, ten 8 | tea |
| 5 | add ten 3 | tea 9, ten 11 | |
| 6 | suggest te | tea 9, ten 11 | ten |
| 7 | suggest tex | no word starts with tex | - |
| 8 | suggest x | no word starts with x | - |
The table follows the totals of the words that start with te. After the third command, tea has 9 and ten has 8. After the fifth, ten has 11. No word starts with tex or with x.
Input: commands = ["add", "add", "suggest"], words = ["bee", "bed", "be"], weights = [4, 4, 0]
Output: ["bed"]Both words have the weight 4. bed comes before bee in the alphabet.
Input: commands = ["suggest"], words = ["a"], weights = [0]
Output: ["-"]The index is empty, so there is no suggestion.
1 ≤ commands.length ≤ 100,000; words and weights have the same length1 ≤ weights[i] ≤ 1,000 for "add" and weights[i] = 0 for "suggest"Looking through every word for each suggestion costs about n × m steps for n suggestions and m words, up to 2.5 × 10^9 at 100,000 commands. A trie finds the node of a prefix in at most 8 steps. If each node stores its best word, a suggestion needs no search at all, and an update touches at most 9 nodes.