#335 · Data structures · Intermediate · 85 XP · about 18 min
A search box suggests words as you type. Build an Autocomplete class:
Autocomplete() starts with no words.add(word) stores a word. Adding a word that is already stored changes nothing.suggest(prefix) returns the first three stored words in alphabetical order that start with prefix, as a list (fewer if fewer words match, and an empty list if none do). A word counts as starting with itself, and the empty prefix matches every word.ac = Autocomplete() for w in ['car', 'card', 'care', 'cart', 'cat', 'dog']: ac.add(w) ac.suggest('car') # returns ['car', 'card', 'care'] ac.suggest('cat') # returns ['cat'] ac.suggest('d') # returns ['dog'] ac.suggest('z') # returns []
add and 20,000 calls of suggest, mixed in any ordersuggest call is too slow at that size.First solves only, ranked by stars and then time.