SDE & MLE Prep

1268. Search Suggestions System

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