Generate Prefix-Based Product Suggestions
CitadelSoftware Engineer · OnsiteLast updated
Generate up to three lexicographically smallest product suggestions for every prefix of a search word, with efficient handling once a prefix has no matches.
Problem
Given distinct lowercase product names and a lowercase search word, return suggestions after each typed character. For every non-empty prefix, return up to three lexicographically smallest products that start with that prefix.
Function Contract
Implement suggested_products(products, search_word) -> list[list[str]].
Constraints
1 <= len(products) <= 50000and each product length is between 1 and 100.1 <= len(search_word) <= 100.- All strings contain only lowercase English letters.
- Products are distinct; the input order does not determine suggestion order.
Examples
- Products
["mobile","mouse","moneypot","monitor","mousepad"]and search word"mouse"produce the standard prefix lists beginning with["mobile","moneypot","monitor"]formandmo. - Once a prefix has no matches, that and all longer prefix lists are empty.
Edge Cases
- Fewer than three matches are returned without padding.
- A product equal to the current prefix is a valid suggestion.
- The first character may have no matching product.
Hints
Hint 1
Limit work per trie node: If using a trie, each node needs only its three smallest suggestions, not every product below it.
Hint 2
Sorted ranges also work: After sorting products, maintain the lower and upper indices whose strings still match the current prefix.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.