Search Suggestions System — LeetCode 1268 Python Solution

MediumTrieArrayStringBinary SearchSortingHeap (Priority Queue)
Problem
#1268
Pattern
Trie
Reading time
6 min

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

Python
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

MeasureComplexity
TimeO(L \times \log n + m)
SpaceO(L) auxiliary

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

On a study list

This problem is on LeetCode 75.

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 \times \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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview