Overview
Suggest words as someone types: sort the dictionary once, then answer each prefix with binary search instead of scanning every word.
- sort once, query many times
- words with a prefix sit side by side
- bisect_left finds the first one
Short Course
Sort the words once: every word starting with a prefix then sits side by
side, and bisect_left finds the first one in O(log n). Trap: scanning
every word on every keystroke costs O(n) per letter typed.
from bisect import bisect_left
words = sorted(["map", "learn", "maple"])
i = bisect_left(words, "ma")
words[i:i + 2] # ['map', 'maple']
Task
Write a class Autocomplete(words) with suggest(prefix): up to 3 words
that start with prefix, in alphabetical order. Example:
Autocomplete(['map', 'lean', 'learn', 'maple']).suggest('le') →
['lean', 'learn'].
Test Suites
Pending
Next
Output