You are given an array of strings products and a string searchWord.
Design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]] Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]. After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]. After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana" Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 10001 <= products[i].length <= 30001 <= sum(products[i].length) <= 2 * 104products are unique.products[i] consists of lowercase English letters.1 <= searchWord.length <= 1000searchWord consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a list of product names and a partial word that someone is typing letter by letter. The brute force approach takes each piece of the typed word, looks at every single product in your list from start to finish, and tests whether that product starts with the typed letters.
Here's how the algorithm would work step-by-step:
def suggested_products(products_list, search_word):
# Sort the products lexicographically first to ensure alphabetical order during selection
sorted_products = sorted(products_list)
suggestions_collection = []
for char_index in range(1, len(search_word) + 1):
current_prefix = search_word[:char_index]
matching_products = []
for single_product in sorted_products:
if single_product.startswith(current_prefix):
matching_products.append(single_product)
# Limit recommendations to a maximum of three items per prefix stage as requested
top_matches = matching_products[:3]
suggestions_collection.append(top_matches)
return suggestions_collectionTo quickly find matching suggestions as someone types, we can organize all available words in a structured tree format where paths spell out the words. As each letter is typed, we simply follow the matching path and gather the first few words we encounter.
Here's how the algorithm would work step-by-step:
class TrieNode:
def __init__(self):
self.child_nodes = {}
self.stored_words = []
class Solution:
def suggestedProducts(self, available_products, search_keyword):
root_node = TrieNode()
available_products.sort()
# Building the tree structure enables efficient prefix matching for every typed character.
for product_name in available_products:
current_node = root_node
for character in product_name:
if character not in current_node.child_nodes:
current_node.child_nodes[character] = TrieNode()
current_node = current_node.child_nodes[character]
if len(current_node.stored_words) < 3:
current_node.stored_words.append(product_name)
search_suggestions = []
current_node = root_node
prefix_matched = True
# We iterate through each letter to gather suggestions progressively as the user types.
for character in search_keyword:
if prefix_matched and character in current_node.child_nodes:
current_node = current_node.child_nodes[character]
search_suggestions.append(current_node.stored_words)
else:
prefix_matched = False
search_suggestions.append([])
return search_suggestions| Case | How to Handle |
|---|---|
| Products array is empty or searchWord is empty | Return an empty list of suggestions immediately since no matches can be generated. |
| Fewer than three products match the typed prefix | Return all available matching products up to a maximum of three without padding or errors. |
| No products match any prefix of the search word | Return empty lists for the current and all subsequent characters of the search word. |
| Products contain duplicate strings | Sorting the products and using a Trie or binary search naturally groups identical strings together in the results. |
| Search word is longer than some or all of the product strings | Prefix matching naturally fails for subsequent characters once the product string length is exceeded, yielding empty lists. |
| Products are not sorted lexicographically initially | Sort the entire products array lexicographically upfront to ensure the top three suggestions are always the alphabetically smallest. |
| Extremely large products array and long search word | Use a Trie data structure or binary search to ensure sub-linear or linear time complexity relative to the input size. |
| Products contain special characters, uppercase letters, or mixed casing | Assume standard lowercase alphanumeric constraints as per problem statement or normalize strings to lower case before processing. |