The problem
A search box shows suggestions while you type. SearchBox(pairs) receives every word with its count (how often people searched for it). suggest(prefix) returns the three words with the highest counts among the words that start with the prefix, highest first. Equal counts are broken by alphabetical order. If fewer than three words match, return them all; if none match, return [].
b = SearchBox([("tea", 5), ("ten", 9), ("team", 2),
("to", 7), ("toe", 1)])
b.suggest("te") # ['ten', 'tea', 'team']
b.suggest("t") # ['ten', 'to', 'tea']
b.suggest("to") # ['to', 'toe']
b.suggest("x") # []
A word counts as starting with itself. Words and prefixes are non-empty and use the letters a to z.
Limits
- Up to 20,000 words of at most 8 letters, and 20,000 suggestions.
- A suggestion must not depend on how many words match: it should cost O(L) for a prefix of length L. Building the search box may cost more.
Builds on TRIE-3 Autocomplete.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Equal counts | Not run | |
| 3 | The prefix is a word | Not run | |
| 4 | Longer than any word | Not run | |
| 5 | Order of adding | Not run | |
| 6 | One letter typed | Not run | |
| 7 | A rare prefix | Not run |