1268. Search Suggestions System - LeetCode Solution


Trie String Binary Search

Python Code:

class Trie:
    def __init__(self, flag = False):
        self.letters = [0] * 27
        self.flag = flag
        
        
        
class Solution:
    def addProducts(self, word, root):
        for letter in word:
            if root.letters[ord(letter) - 97]:
                root = root.letters[ord(letter) -97]
            else:
                root.letters[ord(letter) - 97] = Trie()
                root = root.letters[ord(letter) - 97]
        root.flag = True
        
    def search(self, root, creating):
        a = []
        if not root:
            return a
        if root.flag:
            a.append(creating)
        
        for i in range(len(root.letters)):
            if root.letters[i]:
                a += self.search(root.letters[i], creating + chr(i + 97) )
        return a
            
        
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        root = Trie()
        
        ans = []
        for product in products:
            self.addProducts(product, root)
            
        for i in range(len(searchWord)):
            root_ptr = root
            for letter in searchWord[0: i+1]:
                ind = ord(letter) - 97
                root_ptr = root_ptr.letters[ind]
                if not root_ptr:
                    break
                    
            a = self.search(root_ptr, searchWord[0:i+1])
       
            a.sort()
            ans.append(a[:3])
        return ans


Comments

Submit
0 Comments
More Questions

1530A - Binary Decimal
1472D - Even-Odd Game
441C - Valera and Tubes
1328E - Tree Queries
265A - Colorful Stones (Simplified Edition)
296A - Yaroslav and Permutations
967B - Watering System
152A - Marks
1398A - Bad Triangle
137A - Postcards and photos
1674D - A-B-C Sort
334A - Candy Bags
855A - Tom Riddle's Diary
1417A - Copy-paste
1038A - Equality
1061A - Coins
1676E - Eating Queries
1447A - Add Candies
1721D - Maximum AND
363C - Fixing Typos
1401A - Distance and Axis
658A - Bear and Reverse Radewoosh
1721E - Prefix Function Queries
977E - Cyclic Components
1140D - Minimum Triangulation
75C - Modified GCD
1722A - Spell Check
1722B - Colourblindness
1722D - Line
1722C - Word Game