Contacts

  • + 0 comments

    my solution in python, please comment if you think it can be even faster, sharing is caring

    class TrieNode:
        __slots__ = 'children', 'numberofwordsafter'
        def __init__(self):
            self.children = {}
            self.numberofwordsafter=0
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()
    
        def insert(self, word: str):
            currentNode = self.root
            currentNode.numberofwordsafter +=1
            for c in word:
                if c not in currentNode.children:
                    currentNode.children[c]=TrieNode()
                currentNode = currentNode.children[c]
                currentNode.numberofwordsafter +=1
    
        def numwords(self, word):
            cur_node = self.root
            for c in word:
                if c not in cur_node.children:
                    return 0
                else:
                    cur_node=cur_node.children[c]
            return cur_node.numberofwordsafter
    
    def contacts(queries):
        # Write your code here
        names=Trie()
        results=[]
        for q in queries:
            if q[0]=='add':
                names.insert(q[1])
            else:
                res = names.numwords(q[1])
                results.append(res)
        return results