Ctrl K

Top Three While Typing

Medium
An online store has a product catalog catalog, a list of unique names. A shopper types the string query into the search box one letter at a time. After every letter, the search box shows suggestions: the products whose names start with the part of query typed so far. If more than three products match, it shows the three that come first alphabetically, and the suggestions themselves are listed in alphabetical order. Return a list of length len(query) whose i-th entry holds the suggestions after the first i + 1 letters have been typed. If nothing matches, that entry is an empty list.
Example 1
catalog=["lamp", "lantern", "ladder", "lace", "latch", "mug"], query="lan" → [['lace', 'ladder', 'lamp'], ['lace', 'ladder', 'lamp'], ['lantern']]

After "l" and "la" five items match, and the first three alphabetically are lace, ladder, lamp. After "lan" only lantern is left.

Example 2
catalog=["pen", "pencil"], query="pin" → [['pen', 'pencil'], [], []]

Both items match "p", but nothing starts with "pi", so the remaining lists are empty.

Example 3
catalog=["tea"], query="tea" → [['tea'], ['tea'], ['tea']]
Constraints
  • 1 ≤ len(catalog) ≤ 1000
  • The total length of the names in catalog is at most 2·10⁴
  • All names are distinct, non-empty and made of lowercase English letters
  • 1 ≤ len(query) ≤ 1000, and query consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Searched Words MediumWords Hidden in a Text MediumK-th Smallest in a Sorted Grid MediumNearest k Values MediumWord Grown Letter by Letter Medium
loading Python…
Input
catalog=["lamp", "lantern", "ladder", "lace", "latch", "mug"], query="lan"
Expected
[['lace', 'ladder', 'lamp'], ['lace', 'ladder', 'lamp'], ['lantern']]

Run checks the first 3 tests in your browser. Submit checks all 86 tests on the server, hidden ones included.