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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
7 sort(products.begin(), products.end());
8 vector<vector<string>> result;
9 string prefix;
10 for (char c : searchWord) {
11 prefix += c;
12 vector<string> matches;
13 for (string &product : products) {
14 if (product.compare(0, prefix.size(), prefix) == 0) {
15 matches.push_back(product);
16 if (matches.size() == 3) break;
17 }
18 }
19 result.push_back(matches);
20 }
21 return result;
22}
23
24int main() {
25 vector<string> products = {"mobile","mouse","moneypot","monitor","mousepad"};
26 string searchWord = "mouse";
27 vector<vector<string>> result = suggestedProducts(products, searchWord);
28 for (auto &list : result) {
29 for (auto &prod : list) {
30 cout << prod << " ";
31 }
32 cout << endl;
33 }
34 return 0;
35}
In the C++ implementation, the products are first sorted. We then iterate over each character of the searchWord, creating a prefix, and filter the product list to find matches that start with the prefix, taking the first three.
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 JavaScript Trie implementation involves inserting each product into the Trie structure. As we construct the prefix from searchWord, we navigate the Trie to gather up to three suggestions efficiently, leveraging the sorted nature for lexicographic ordering.