MediumNo. 1268
Search Suggestions System — LeetCode 1268 Python Solution
- Pattern
- Trie
- Topics
- Trie, Array, String, Binary Search, Sorting, Heap (Priority Queue)
- On a study list
- LeetCode 75
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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.
Example
- 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"].
Python solution
class Trie:
def __init__(self):
self.children: List[Union[Trie, None]] = [None] * 26
self.v: List[int] = []
def insert(self, w, i):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
if len(node.v) < 3:
node.v.append(i)
def search(self, w):
node = self
ans = [[] for _ in range(len(w))]
for i, c in enumerate(w):
idx = ord(c) - ord('a')
if node.children[idx] is None:
break
node = node.children[idx]
ans[i] = node.v
return ans
class Solution:
def suggestedProducts(
self, products: List[str], searchWord: str
) -> List[List[str]]:
products.sort()
trie = Trie()
for i, w in enumerate(products):
trie.insert(w, i)
return [[products[i] for i in v] for v in trie.search(searchWord)]Complexity
- Time
- O(L × log n + m)
- Space · auxiliary
- O(L)
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 1268. Search Suggestions System is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0378 | Kth Smallest Element in a Sorted Matrix | Medium |
| 1337 | The K Weakest Rows in a Matrix | Easy |
| 1648 | Sell Diminishing-Valued Colored Balls | Medium |
| 1851 | Minimum Interval to Include Each Query | Hard |
| 2054 | Two Best Non-Overlapping Events | Medium |
| 2333 | Minimum Sum of Squared Difference | Medium |
Frequently asked questions
- How hard is LeetCode 1268. Search Suggestions System?
LeetCode 1268. Search Suggestions System is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1268. Search Suggestions System?
The Python solution on this page runs in O(L × log n + m).
- What is the space complexity of LeetCode 1268. Search Suggestions System?
The Python solution on this page uses O(L) auxiliary space.
- What topics does LeetCode 1268. Search Suggestions System cover?
LeetCode 1268. Search Suggestions System is tagged Trie, Array, String, Binary Search, Sorting and Heap (Priority Queue) on LeetCode.