Contacts

  • + 0 comments
    from collections import defaultdict
    
    class Node:
        def __init__(self):
            self.char = defaultdict(Node)
            self.count = 0
            
    class Trie:
        def __init__(self):
            self.root = Node()
        
        def add(self, name: str) -> None:
            curr_node = self.root
            for c in name:
                curr_node = curr_node.char[c]
                curr_node.count += 1
            
        def find(self, name: str) -> int:
            curr_node = self.root
            for c in name:
                if c not in curr_node.char:
                    return 0
                curr_node = curr_node.char[c]
            return curr_node.count
    
    def contacts(queries):
        trie = Trie()
        result = []
        for op, name in queries:
            if op == 'add':
                trie.add(name)
            elif op == 'find':
                result.append(trie.find(name))
        return result