{"id":5841,"date":"2019-11-24T00:06:55","date_gmt":"2019-11-24T08:06:55","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=5841"},"modified":"2019-11-24T17:34:10","modified_gmt":"2019-11-25T01:34:10","slug":"leetcode-1268-search-suggestions-system","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/algorithms\/binary-search\/leetcode-1268-search-suggestions-system\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1268. Search Suggestions System"},"content":{"rendered":"\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 1268. Search Suggestions System - \u5237\u9898\u627e\u5de5\u4f5c EP268\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/hi8xga8nWm4?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>Given an array of strings&nbsp;<code>products<\/code>&nbsp;and a string&nbsp;<code>searchWord<\/code>. We want to design a system that suggests at most three product names from&nbsp;<code>products<\/code>&nbsp;after each character of&nbsp;<code>searchWord<\/code>&nbsp;is typed. Suggested products should have common prefix with the searchWord. If there are&nbsp;more than three products with a common prefix&nbsp;return the three lexicographically minimums products.<\/p>\n\n\n\n<p>Return&nbsp;<em>list of lists<\/em>&nbsp;of the suggested&nbsp;<code>products<\/code>&nbsp;after each character of&nbsp;<code>searchWord<\/code>&nbsp;is typed.&nbsp;<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\n<strong>Output:<\/strong> [\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\n<strong>Explanation:<\/strong> products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> products = [\"havana\"], searchWord = \"havana\"\n<strong>Output:<\/strong> [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\n<strong>Output:<\/strong> [[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]\n<\/pre>\n\n\n\n<p><strong>Example 4:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> products = [\"havana\"], searchWord = \"tatiana\"\n<strong>Output:<\/strong> [[],[],[],[],[],[],[]]\n<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>1 &lt;= products.length &lt;= 1000<\/code><\/li><li><code>1 &lt;= \u03a3 products[i].length &lt;= 2 * 10^4<\/code><\/li><li>All characters of&nbsp;<code>products[i]<\/code>&nbsp;are lower-case English letters.<\/li><li><code>1 &lt;= searchWord.length &lt;= 1000<\/code><\/li><li>All characters of&nbsp;<code>searchWord<\/code>&nbsp;are lower-case English letters.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution 1: Binary Search<\/strong><\/h2>\n\n\n\n<p>Sort the input array and do two binary searches.<br>One for prefix of the search word as lower bound, another for prefix + &#8216;~&#8217; as upper bound.<br>&#8216;~&#8217; &gt; &#8216;z&#8217;<\/p>\n\n\n\n<p>Time complexity: O(nlogn + l * logn)<br>Space complexity: O(1)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"C++\">\n\/\/ Author: Huahua, 36ms, 35MB\nclass Solution {\npublic:\n  vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n    vector<vector<string>> ans;\n    std::sort(begin(products), end(products));\n    string key;\n    for (char c : searchWord) {\n      key += c;      \n      auto l = lower_bound(begin(products), end(products), key);\n      auto r = upper_bound(begin(products), end(products), key += '~');\n      if (l == r) break; \/\/ early return\n      key.pop_back();\n      ans.emplace_back(l, min(l + 3, r));\n    }\n    while (ans.size() != searchWord.length()) ans.push_back({});\n    return ans;\n  }\n};\n<\/pre>\n<\/div><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution 2: Trie<\/strong><\/h2>\n\n\n\n<p>Initialization: Sum(len(products[i]))<br>Query: O(len(searchWord))<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"C++\">\n\/\/ Author: Huahua, 148 ms, 98.8 MB\nstruct Trie {\n  Trie(): nodes(26) {}\n  ~Trie() { \n    for (auto* node : nodes)\n      delete node;\n  }\n  vector<Trie*> nodes;\n  vector<const string*> words;  \n  \n  static void addWord(Trie* root, const string& word) {    \n    for (char c : word) {      \n      if (root->nodes[c - 'a'] == nullptr) root->nodes[c - 'a'] = new Trie();\n      root = root->nodes[c - 'a'];\n      if (root->words.size() < 3)\n        root->words.push_back(&word);\n    }\n  }\n  \n  static vector<vector<string>> getWords(Trie* root, const string& prefix) {\n    vector<vector<string>> ans(prefix.size());\n    for (int i = 0; i < prefix.size(); ++i) {\n      char c = prefix[i];\n      root = root->nodes[c - 'a'];\n      if (root == nullptr) break;\n      for (auto* word : root->words)\n        ans[i].push_back(*word);\n    }\n    return ans;\n  }\n};\n\nclass Solution {\npublic:\n  vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {\n    std::sort(begin(products), end(products));\n    Trie root;\n    for (const auto& product : products)\n      Trie::addWord(&root, product);\n    return Trie::getWords(&root, searchWord);\n  }\n};\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Given an array of strings&nbsp;products&nbsp;and a string&nbsp;searchWord. We want to design a system that suggests at most three product names from&nbsp;products&nbsp;after each character of&nbsp;searchWord&nbsp;is typed.&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[149],"tags":[52,177,97,15,96],"class_list":["post-5841","post","type-post","status-publish","format-standard","hentry","category-binary-search","tag-binary-search","tag-medium","tag-prefix","tag-sorting","tag-trie","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5841","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=5841"}],"version-history":[{"count":5,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5841\/revisions"}],"predecessor-version":[{"id":5849,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/5841\/revisions\/5849"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=5841"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=5841"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=5841"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}