Search Suggestions System Problem
Description
LeetCode Problem 1268.
You are given an array of strings products and a string searchWord.
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 searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord is typed.
Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"].
After typing mou, mous and mouse the system suggests ["mouse","mousepad"].
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Explanation: The only word "havana" will be always suggested while typing the search word.
Constraints:
1 <= products.length <= 10001 <= products[i].length <= 30001 <= sum(products[i].length) <= 2 * 10^4- All the strings of
productsare unique. products[i]consists of lowercase English letters.1 <= searchWord.length <= 1000searchWordconsists of lowercase English letters.
Solution
Approach: Sorting + Trie
After each typed character we need the three lexicographically smallest products that start with the current prefix. A trie groups words by prefix: all products with prefix p lie in the subtree under the node for p.
The trick is to sort products first and then insert them in that order. While inserting a word, every node it passes through is one of its prefixes, and we append the word's index to that node's list if the list holds fewer than three. Because the words arrive in sorted order, each node ends up with exactly the three smallest products under it, with no searching of the subtree later.
To answer, walk down the trie along searchWord, one character at a time, and turn each node's list of indexes back into product names. If some prefix has no node, no product starts with it, and none starts with any longer prefix either, so that position and all the following ones get an empty list. This also covers a searchWord longer than every product.
Complexity: with L the total length of all products and n their count, sorting takes O(L log n) (comparisons of strings), building the trie O(L), and the search O(m) for a searchWord of length m plus the size of the output. The trie uses O(L) space.
class Trie:
def __init__(self):
self.children = [None] * 26
self.top = [] # indexes of the (at most 3) smallest products with this prefix
def insert(self, word: str, index: int) -> None:
node = self
for c in word:
k = ord(c) - ord('a')
if node.children[k] is None:
node.children[k] = Trie()
node = node.children[k]
if len(node.top) < 3:
node.top.append(index)
def search(self, word: str) -> List[List[int]]:
node = self
result = [[] for _ in word]
for i, c in enumerate(word):
node = node.children[ord(c) - ord('a')]
if node is None:
break # no product has this prefix, nor any longer one
result[i] = node.top
return result
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort() # insertion order is now lexicographic order
trie = Trie()
for i, word in enumerate(products):
trie.insert(word, i)
return [[products[i] for i in top] for top in trie.search(searchWord)]