Sponsored
Sponsored
This approach involves sorting the products array first and then iteratively constructing prefixes from the searchWord. For each prefix, use a simple linear search over the sorted products array to find matches. By keeping the products sorted, it ensures that we can easily pick the smallest lexicographical options.
After sorting, for every prefix of the searchWord, we traverse the sorted products list, check if the product starts with the current prefix, and collect up to three matches.
Time Complexity: O(n log n) due to sorting, where n is the length of products. Each prefix search is O(n), leading to an overall complexity of O(n log n + m * n), where m is the length of searchWord.
Space Complexity: O(1) additional space is needed outside the result storage, although storing results may take O(m * 3) space.
1function suggestedProducts(products, searchWord) {
2 products.sort();
3 let result = [];
4 let prefix = '';
5 for (let char of searchWord) {
6 prefix += char;
7 let matches = products.filter(product => product.startsWith(prefix)).slice(0, 3);
8 result.push(matches);
9 }
10 return result;
11}
12
13// Example usage:
14const products = ["mobile","mouse","moneypot","monitor","mousepad"];
15const searchWord = "mouse";
16console.log(suggestedProducts(products, searchWord));
The JavaScript solution involves initially sorting the products. As we iterate over the characters in searchWord, it accumulates a prefix and selects up to three matches using array filters.
This approach aims at using a Trie to efficiently handle prefix matching. With a Trie, we insert all product names into the Trie. As each character is typed in the searchWord, we traverse the Trie to check for the top three lexicographical matches.
Using a Trie allows us to handle the prefix matching efficiently by navigating through the structure step by step according to the current prefix.
Time Complexity: O(n m) to insert all products (where n is number of products and m is max product length), and O(k) to search for each prefix (where k is the length of searchWord).
Space Complexity: O(n m) for the Trie storage, since we store each character of every word.
1
This Python code uses a Trie structure. We create nodes for each character and keep track of the top three suggestions within the TrieNode. As searchWord is typed, we navigate the Trie and retrieve suggestions.