Don't use Trie -> too hard to implement
The eaiest way to do is using two pointers with sorted products, move the l, r pointer forward while unmatch, then append the matching first three products each time.
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
l, r = 0, len(products) - 1
products.sort()
results = []
for i, word in enumerate(searchWord):
while l <= r and (len(products[l]) <= i or products[l][i] != word):
l += 1
while l <= r and (len(products[r]) <= i or products[r][i] != word):
r -= 1
if l <= r:
results.append(products[l:min(l + 3, r + 1)])
else:
results.append([])
return results
Don't use Trie -> too hard to implement The eaiest way to do is using two pointers with sorted products, move the l, r pointer forward while unmatch, then append the matching first three products each time.