[LeetCode] Search Suggestions System

1268. Search Suggestions System

Given an array of strings products and a string searchWord. We want to 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 the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

Return list of lists of the suggested products after each character of searchWord is typed.

Trie Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
struct Trie {
Trie *next[26];
bool fin;

Trie() : fin(false) {
memset(next, 0, sizeof(next));
}

~Trie() {
for (int i = 0; i < 26; i++)
if (next[i] != 0)
delete next[i];
}

void insert(const char *key) {
if (neof(*key)) {
if (!next[*key - 'a']) next[*key - 'a'] = new Trie();
next[*key - 'a']->insert(key + 1);
} else
fin = true;
}

void lexicographicallyGet(vector<string> &res, int &count, string prefix = "") {
if (!count) return;
if (fin) {
res.push_back(prefix);
count--;
}
if (!count) return;
for (int i = 0; i < 26; ++i) {
if (!next[i]) continue;
next[i]->lexicographicallyGet(res, count, prefix + (char)('a' + i));
}
}

Trie *get(char c) {
return next[c - 'a'];
}

bool neof(char c) {
return 'a' <= c && c <= 'z';
}
};

class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string> &products, string searchWord) {
Trie* trie = new Trie();
string prefix;
vector<vector<string>> res;
for(auto& p : products) {
if(p[0] != searchWord[0]) continue;
trie->insert(p.c_str());
}

for(auto& c : searchWord) {
prefix += c;
if(!trie) {
res.push_back({});
} else {
trie = trie->get(c);
if(!trie) {
res.push_back({});
} else {
vector<string> tmp;
int cnt = 3;
trie->lexicographicallyGet(tmp, cnt, prefix);
res.push_back(tmp);
}
}
}
return res;
}
};

Binary Search Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string> &p, string s) {
vector<vector<string>> res(s.size(), vector<string>());
sort(p.begin(), p.end());
auto it = begin(p);
string prefix = "";
for(auto& c : s) {
prefix += c;
it = lower_bound(it, end(p), prefix);
for(int i = 0; i < 3 && (it + i) != end(p) && (it + i)->find(prefix); ++i) {
res[prefix.length() - 1].push_back(*(it + i));
}
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/07/PS/LeetCode/search-suggestions-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.