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.
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"].
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.
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.The simplest solution to this problem is to sort the list of products first. For every typed prefix, we can iterate through all the products and check if a product starts with this prefix. If it does, we add it to our result list for that prefix until we have added 3 suggestions or exhausted the list.
products array.products list and check if the product starts with the current prefix.n is the number of products and m is the length of the searchWord. Sorting costs O(n log n) and the nested loop costs O(m * n).We can use a Trie to represent all product names efficiently. For each character typed, we traverse the Trie to find the node representing that prefix and perform a DFS to gather the top 3 lexicographical suggestions.
m is the total number of characters in all products (for Trie insertion), n log n for sorting, and l * m is the sum of lengths of all prefixes multiplied by max suggestions (constant time for each prefix)m is the total number of characters stored in the Trie.This approach utilizes binary search to find the starting point of the valid suggestions in the sorted products array. The addition of two pointers helps in efficiently reducing the search space as we progress through each character in the search word.
products array.m is the length of the searchWord, and n is the number of products. Sorting takes O(n log n), and the search using two pointers costs O(m) for narrowing the range for each prefix.