Search Box Suggestions
Implement a class SearchBox that suggests searches while someone types. It remembers how often every phrase was searched and offers the most popular phrases that begin with what has been typed so far. Write these methods:
SearchBox(limit)starts with no phrases and nothing typed. At mostlimitsuggestions are shown.record(phrase, times)addstimessearches to the count ofphrase.type_letter(ch)adds the characterchto what is typed and returns the suggestions: the remembered phrases that begin with the typed text, most often searched first. Equally popular phrases come in alphabetical order. Only the firstlimitof them are returned.submit()sends what is typed: that text gets one more search, the box is emptied, and the text is returned. With nothing typed it returns""and counts nothing.clear()empties the box without counting anything.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
SearchBox(2)
record("cat", 2)
record("cab", 3)
type_letter("c") returns ["cab","cat"]
type_letter("a") returns ["cab","cat"]
type_letter("t") returns ["cat"]
submit() returns "cat"
type_letter("c") returns ["cab","cat"]
After typing c, both phrases fit and cab, searched 3 times, comes before cat. Typing a and t leaves only cat. Submitting counts cat once more, so now both phrases have 3 searches and the alphabet decides.
Constraints
1 <= limit <= 5- phrases are 1 to 8 characters: lowercase letters and single spaces, with no space at either end
- the typed text follows the same rules, except that it may end with a space while it is being typed
1 <= times <= 3- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Classes problems
- Spreadsheet Sums Without CyclesHard
- Tiny DiskHard
- Tray of WeightsHard
- Two-Tier CacheHard
- Bank Account Without OverdraftsBeginner
- Grid With Row and Column AddsBeginner
- Guest Book SignaturesBeginner
- Odometer With a Trip MeterBeginner