#1268

Search Suggestions System

Medium
ArrayStringBinary SearchTrieSortingHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m)Space O(n * m)

The optimal solution uses a Trie (prefix tree) to efficiently store and retrieve suggestions based on prefixes. This allows for quick lookups as we build the searchWord character by character.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a Trie from the sorted products list.
  2. 2Step 2: For each character in searchWord, traverse the Trie to find matching products.
  3. 3Step 3: Collect at most three suggestions for each prefix and store them in a result list.
solution.py33 lines
1# Full working Python code
2class TrieNode:
3    def __init__(self):
4        self.children = {}
5        self.products = []
6
7class Trie:
8    def __init__(self):
9        self.root = TrieNode()
10
11    def insert(self, product):
12        node = self.root
13        for char in product:
14            if char not in node.children:
15                node.children[char] = TrieNode()
16            node = node.children[char]
17            if len(node.products) < 3:
18                node.products.append(product)
19
20def suggestedProducts(products, searchWord):
21    products.sort()
22    trie = Trie()
23    for product in products:
24        trie.insert(product)
25    result = []
26    node = trie.root
27    for char in searchWord:
28        if char in node.children:
29            node = node.children[char]
30        else:
31            node = TrieNode()
32        result.append(node.products)
33    return result

Complexity note: The time complexity is O(n * m) where n is the number of products and m is the maximum length of a product. This is due to inserting each product into the Trie. The space complexity is O(n * m) for storing the Trie structure.

  • 1Sorting the products is crucial for lexicographical order.
  • 2Using a Trie allows for efficient prefix searching.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.