<p>You are given an array of strings <code>products</code> and a string <code>searchWord</code>.</p>

<p>Design a system that suggests at most three product names from <code>products</code> after each character of <code>searchWord</code> is typed. Suggested products should have common prefix with <code>searchWord</code>. If there are more than three products with a common prefix return the three lexicographically minimums products.</p>

<p>Return <em>a list of lists of the suggested products after each character of </em><code>searchWord</code><em> is typed</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> products = [&quot;mobile&quot;,&quot;mouse&quot;,&quot;moneypot&quot;,&quot;monitor&quot;,&quot;mousepad&quot;], searchWord = &quot;mouse&quot;
<strong>Output:</strong> [[&quot;mobile&quot;,&quot;moneypot&quot;,&quot;monitor&quot;],[&quot;mobile&quot;,&quot;moneypot&quot;,&quot;monitor&quot;],[&quot;mouse&quot;,&quot;mousepad&quot;],[&quot;mouse&quot;,&quot;mousepad&quot;],[&quot;mouse&quot;,&quot;mousepad&quot;]]
<strong>Explanation:</strong> products sorted lexicographically = [&quot;mobile&quot;,&quot;moneypot&quot;,&quot;monitor&quot;,&quot;mouse&quot;,&quot;mousepad&quot;].
After typing m and mo all products match and we show user [&quot;mobile&quot;,&quot;moneypot&quot;,&quot;monitor&quot;].
After typing mou, mous and mouse the system suggests [&quot;mouse&quot;,&quot;mousepad&quot;].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> products = [&quot;havana&quot;], searchWord = &quot;havana&quot;
<strong>Output:</strong> [[&quot;havana&quot;],[&quot;havana&quot;],[&quot;havana&quot;],[&quot;havana&quot;],[&quot;havana&quot;],[&quot;havana&quot;]]
<strong>Explanation:</strong> The only word &quot;havana&quot; will be always suggested while typing the search word.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= products.length &lt;= 1000</code></li>
	<li><code>1 &lt;= products[i].length &lt;= 3000</code></li>
	<li><code>1 &lt;= sum(products[i].length) &lt;= 2 * 10<sup>4</sup></code></li>
	<li>All the strings of <code>products</code> are <strong>unique</strong>.</li>
	<li><code>products[i]</code> consists of lowercase English letters.</li>
	<li><code>1 &lt;= searchWord.length &lt;= 1000</code></li>
	<li><code>searchWord</code> consists of lowercase English letters.</li>
</ul>

# 2024/09/17
# 面试前刷Doordash的高频题
#
# 题目要求和System design的时候一样
# All the strings of products are unique.
# 还是Tire
# 但和System design时候不一样的是，这里只需要不会有重复元素，所以不用计数
# 每个node记录以此为prefix的三个word，按照字母排序最前面的三个
# 复杂度是O(n * k)
# 但对于这题，因为只有一个search word，可以custom search，但复杂度是O(nlogn * k)，没有更优，而且lambda不好写
# 还是Tire
class Node(object):
    def __init__(self, char):
        self.char = char
        self.children = {}
        self.suggestions = []
        # self.is_name = False

class Solution:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        root = Node(None)

        for product in products:
            self.create(root, product)

        return self.search(root, searchWord)


    def create(self, root, word):
        cur = root

        # for char in word:
        #     if char in cur.children:
        #         if len(cur.suggestions) < 3:
        #             cur.suggestions.append(word)
        #         else:
        #             cur.suggestions.append(word)
        #             cur.suggestions.sort()
        #             cur.suggestions.pop()
        #         cur = cur.children[char]
        #     else:
        #         node = Node(char)
        #         node.suggestions.append(word)
        #         cur.children[char] = node
        #         cur = node
        # 有问题，我存suggestion的地方错了
        # 改动很简单，cur更新之后再去加就对了
        # 其实就是cur的物理意义没正确理解，更新前是当前char
        for char in word:
            if char in cur.children:
                cur = cur.children[char]
            else:
                node = Node(char)
                cur.children[char] = node
                cur = node
            if len(cur.suggestions) < 3:
                cur.suggestions.append(word)
            else:
                cur.suggestions.append(word)
                cur.suggestions.sort()
                cur.suggestions.pop()


    def search(self, root, word):
        cur = root
        result = []

        # i = 0
        # while i < len(word):
        #     char = word[i]
        #     if i > 0:
        #         cur.suggestions.sort()
        #         result.append(cur.suggestions)
        #     if char in cur.children:
        #         cur = cur.children[char]
        #     else:
        #         break
        #     i += 1

        # if i == len(word):
        #     cur.suggestions.sort()
        #     result.append(cur.suggestions)
        # 没问题，但可以优化一下实现
        for char in word:
            if char in cur.children:
                cur = cur.children[char]
                cur.suggestions.sort()
                result.append(cur.suggestions)
            else:
                cur = Node(None) # 这个不要忘了
                result.append([]) # 为了正确输出结果

        return result
# 有问题，我存suggestion的地方错了
# 主要原因是cur的物理意义没正确理解
# 这题还有一个办法是教案上讲过的prefix + DFS
# 答案在DFS的时候，因为字母只有26个，按照顺序去找，肯定能找到字母排序最小的三个（不是很喜欢，容易弄错）
# 因为还是多种方法，需要正确分析复杂度
# 上面的方法，因为suggestions是固定size的，所以sort的操作复杂度是O(1)（除非考虑word的长度，一般sort的时候不考虑）
# Time: O(M) to build the trie where M is total number of characters in products
#       search 的时候是O(len(searchWord))，所以只需要考虑前者
# Space: O(n), Here n is the number of nodes in the trie
# 我上面还有一个办法，先sort products，如：
# https://leetcode.com/problems/search-suggestions-system/solutions/508775/python-trie-sort-trie-heap
# 这样按照顺序加进去，suggestion的前三个一定是排序最小的，复杂度分析有点不一样，但差别不大，代码会简单点
# 最后还有一种sorted的办法，实现起来最简单，也是要知道
# https://leetcode.com/problems/search-suggestions-system/solutions/436674/c-java-python-sort-and-binary-search-the-prefix
# In a sorted list of words,
# for any word A[i],
# all its sugested words must following this word in the list.
# For example, if A[i] is a prefix of A[j],
# A[i] must be the prefix of A[i + 1], A[i + 2], ..., A[j]
# Time O(NlogN) for sorting
# Space O(logN) for quick sort.
# Time O(logN) for each query
# Space O(query) for each query
# where I take word operation as O(1)
# 最后 Time = O(nlogn + mlogn) m是searchWord的长度，和上面方法比，不好讲哪个更快，需要分类讨论
class Solution:
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        products.sort()

        prefix = ""
        result = []

        for char in searchWord:
            prefix += char
            # i = bisect.bisect(products, prefix) # 原来不指定的时候默认是bisect_right
            i = bisect.bisect_left(products, prefix)
            result.append([w for w in products[i:i + 3] if w.startswith(prefix)])

        return result


19800