Taro Logo

Search Suggestions System

#3 Most AskedMedium
1 view
Topics:
ArraysStringsBinary Search

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 <= 1000
  • 1 <= products[i].length <= 3000
  • 1 <= sum(products[i].length) <= 2 * 104
  • All the strings of products are unique.
  • products[i] consists of lowercase English letters.
  • 1 <= searchWord.length <= 1000
  • searchWord consists of lowercase English letters.

Solution


Clarifying Questions

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:

  1. Are the strings in the `products` array guaranteed to be lowercase English letters, and should the search be case-sensitive?
  2. If there are fewer than three matching products for a typed prefix, should we return all available matches, or pad the result in any specific way?
  3. Do the suggested products need to be returned in a specific sorted order (e.g., lexicographically), and should the initial `products` array be assumed unsorted?
  4. How should duplicate product names in the `products` input array be handled in the suggested results?
  5. What should be returned if no products share a common prefix with the currently typed prefix of `searchWord`?

Brute Force Solution

Approach

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:

  1. Look at the first letter of the search word.
  2. Go through the entire list of products one by one, checking if each product begins with that first letter.
  3. Collect all the products that match, sort them alphabetically, and keep only the top few.
  4. Now look at the first two letters of the search word combined.
  5. Go through the entire list of products again from the very beginning, checking which ones start with these first two letters.
  6. Collect those matches, sort them alphabetically, and save the top few.
  7. Repeat this exact same checking process for every growing prefix of the search word until you have built recommendations for every stage of typing.

Code Implementation

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_collection

Big(O) Analysis

Time Complexity
O(m * n * m) – To analyze the time complexity, let n be the number of products in our list and m be the length of the search word. For each of the m prefixes formed as the user types, the algorithm scans all n products from the beginning to check for a prefix match. Each string comparison takes up to m operations to verify the characters. This results in approximately m * n * m operations, which simplifies to O(m squared * n).
Space Complexity
O(N * M) – To implement the search suggestions system described in the plain English steps, we allocate auxiliary space to store the output results for each prefix of the search word. Specifically, we maintain a collection of lists to hold up to three matching products for each of the M letters in the search word, where N represents the number of products in the input list. The sorting and filtering process requires temporary data structures to hold the matching subsets at each typing stage before retaining the top few recommendations. As both the number of products N and the length of the search word M scale, the extra memory required to build and return these intermediate lists grows proportionally. Simplifying this storage requirement to Big O notation yields O(N * M) auxiliary space.

Optimal Solution

Approach

To 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:

  1. Take all the available words and build a connected tree structure where every branch represents a letter, allowing us to spell out any word from the starting point.
  2. When the user types a new letter, move one step deeper down the tree along the branch that matches that letter.
  3. If at any point there is no branch matching the typed letter, stop searching because no words exist that match what has been typed so far.
  4. Whenever we are at our current position in the tree, look ahead and collect up to three complete words that can be formed by following the easiest paths forward.
  5. Repeat this collection process for every single letter the user types, gradually adding more letters to the search until the entire product name is entered.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(M * L + L^2 * S) – Building the tree takes O(M * L) time, where M is the number of words and L is the maximum length of a word, because we insert each character of every word into the tree. As the user types each of the L characters in the search query, we traverse the tree and collect up to 3 words, which takes O(L * S) time per character where S is the number of suggestions retrieved. Repeating this collection for each of the L typed characters results in L times O(L * S), which simplifies to O(L^2 * S). Combining the tree construction and the search phase gives a total time complexity of O(M * L + L^2 * S).
Space Complexity
O(M * L + Q) – The extra space is driven by the structured tree format, where M is the number of available words and L is the average length of a word, requiring memory proportional to the total characters to store all connected branches. Additionally, as the user types each letter of the query string of length Q, temporary lists hold up to three matching suggestions at each step. This means the auxiliary space grows directly with both the total size of the vocabulary tree and the length of the search query.

Edge Cases

Products array is empty or searchWord is empty
How to Handle:
Return an empty list of suggestions immediately since no matches can be generated.
Fewer than three products match the typed prefix
How to Handle:
Return all available matching products up to a maximum of three without padding or errors.
No products match any prefix of the search word
How to Handle:
Return empty lists for the current and all subsequent characters of the search word.
Products contain duplicate strings
How to Handle:
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
How to Handle:
Prefix matching naturally fails for subsequent characters once the product string length is exceeded, yielding empty lists.
Products are not sorted lexicographically initially
How to Handle:
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
How to Handle:
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
How to Handle:
Assume standard lowercase alphanumeric constraints as per problem statement or normalize strings to lower case before processing.
0/4 completed