We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The following simple code worked for me. Since the length of name is less than 22, both time complexity and space complexity are O(n).
fromcollectionsimportdefaultdictdefcontacts(queries):# Write your code hererecord=defaultdict(int)ans=[]foroperation,nameinqueries:ifoperation=='add':foriinrange(len(name)):record[name[:i+1]]+=1else:ans.append(record[name])returnans
my solution in python, please comment if you think it can be even faster, sharing is caring
classTrieNode:__slots__='children','numberofwordsafter'def__init__(self):self.children={}self.numberofwordsafter=0classTrie:def__init__(self):self.root=TrieNode()definsert(self,word:str):currentNode=self.rootcurrentNode.numberofwordsafter+=1forcinword:ifcnotincurrentNode.children:currentNode.children[c]=TrieNode()currentNode=currentNode.children[c]currentNode.numberofwordsafter+=1defnumwords(self,word):cur_node=self.rootforcinword:ifcnotincur_node.children:return0else:cur_node=cur_node.children[c]returncur_node.numberofwordsafterdefcontacts(queries):# Write your code herenames=Trie()results=[]forqinqueries:ifq[0]=='add':names.insert(q[1])else:res=names.numwords(q[1])results.append(res)returnresults
Java O(n L)
The following simple code worked for me. Since the length of name is less than 22, both time complexity and space complexity are O(n).
my solution in python, please comment if you think it can be even faster, sharing is caring