Search Suggestions System

Problem Summary

Key Observations

Approach Taken

Why This Works

Time & Space Complexity

Code

class TrieNode:
    def __init__(self):
        self.children = {}
        self.suggestions = []

class Solution:
    def suggestedProducts(
        self, products: List[str], searchWord: str
    ) -> List[List[str]]:
        # pre-sort products
        products.sort()

        # first part: store all products in a prefix tree
        # at each letter we need to store the first three words, store the current working word if not hit the 3 limit
        prefixTreeRoot = TrieNode()

        for product in products:
            cur = prefixTreeRoot
            for letter in product:
                if letter not in cur.children:
                    cur.children[letter] = TrieNode()
                cur = cur.children[letter]
                if len(cur.suggestions) < 3:
                    cur.suggestions.append(product)

        # second part: get 3 product recommendation for each letter typed in searchWord
        suggestions = [[] for _ in range(len(searchWord))]
        cur = prefixTreeRoot
        for i, letter in enumerate(searchWord):
            if letter not in cur.children:
                return suggestions
            cur = cur.children[letter]
            suggestions[i] = cur.suggestions
        return suggestions

Common Mistakes / Things I Got Stuck On