TRIE-P3

Search box suggestions

Practice 3 of 5Tries7 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

7 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Equal countsNot run
3The prefix is a wordNot run
4Longer than any wordNot run
5Order of addingNot run
6One letter typedNot run
7A rare prefixNot run