1268. Search Suggestions System
Asked at 17Amazon44Google21Microsoft20Bloomberg14Meta8.5Squarepoint Capital96Wix87DoorDash85UBS85Docusign82Anduril66Twilio64Citadel57PayPal42Oracle41TikTok35Uber22
Problem
As each character of searchWord is typed, suggest up to three products that start with the prefix typed so far, choosing the lexicographically smallest ones. Return the suggestion list after every character.
Example: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" → [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Sort the products once. For each typed prefix, binary-search its lower bound; the next 3 products that start with the prefix are the suggestions. (A trie storing the top-3 at each node is the alternative.)
Complexity: O(n log n + L log n).
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
res, prefix = [], ""
for ch in searchWord:
prefix += ch
i = bisect.bisect_left(products, prefix)
res.append([p for p in products[i:i + 3] if p.startswith(prefix)])
return res
P = ["mobile", "mouse", "moneypot", "monitor", "mousepad"]
assert Solution().suggestedProducts(P, "mouse") == [
["mobile", "moneypot", "monitor"], ["mobile", "moneypot", "monitor"],
["mouse", "mousepad"], ["mouse", "mousepad"], ["mouse", "mousepad"]]
assert Solution().suggestedProducts(["havana"], "tatiana") == [[], [], [], [], [], [], []]
assert Solution().suggestedProducts(["bags", "baggage", "banner", "box", "cloths"], "bags") == [["baggage", "bags", "banner"], ["baggage", "bags", "banner"], ["baggage", "bags"], ["bags"]]
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
List<List<String>> res = new ArrayList<>();
String prefix = "";
for (char c : searchWord.toCharArray()) {
prefix += c;
int lo = 0, hi = products.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (products[mid].compareTo(prefix) >= 0) hi = mid; else lo = mid + 1;
}
List<String> cur = new ArrayList<>();
for (int i = lo; i < Math.min(lo + 3, products.length) && products[i].startsWith(prefix); i++) cur.add(products[i]);
res.add(cur);
}
return res;
}
}
func suggestedProducts(products []string, searchWord string) [][]string {
sort.Strings(products)
res := [][]string{}
for k := 1; k <= len(searchWord); k++ {
prefix := searchWord[:k]
i := sort.SearchStrings(products, prefix) // first product >= prefix
group := []string{}
for j := i; j < len(products) && j < i+3 && strings.HasPrefix(products[j], prefix); j++ {
group = append(group, products[j])
}
res = append(res, group)
}
return res
}