Skip to content
BytePatterns

Typeahead Top Three

MediumTries#trie#prefix-match~30m

Problem

A shop has a list of distinct lowercase product names. A customer types a search word one character at a time. After each character, suggest up to three product names that start with everything typed so far, choosing the alphabetically smallest ones. Return one list of suggestions per typed character.

Examples

Input:  products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"], word = "mouse"
Output: [["mobile", "moneypot", "monitor"],
         ["mobile", "moneypot", "monitor"],
         ["mouse", "mousepad"],
         ["mouse", "mousepad"],
         ["mouse", "mousepad"]]
Input:  products = ["bag", "bags", "banner", "box"], word = "bax"
Output: [["bag", "bags", "banner"], ["bag", "bags", "banner"], []]
Why:    once no product matches, it stays that way for longer prefixes
Input:  products = ["bag"], word = "cat"
Output: [[], [], []]
Why:    edge case, not even the first character matches

Hints

0 / 3

Stuck on the idea rather than the code? Prefix Search covers it.