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.
# Node of a prefix treeclassNode:def__init__(self):self.children={}self.EndOfWord=False# Trie data structureclassTrie:def__init__(self):'''Initializeaprefixtreewitharootnode.'''self.root=Node()definsert(self,word:str)->bool:'''Insertawordintotheprefixtree.ReturnTrueifanyexistingwordisaprefixofcurrentlyinsertedword.Else,returnFalse.'''current=self.rootflag=Falseforcinword:ifcnotincurrent.children:current.children[c]=Node()current=current.children[c]ifcurrent.EndOfWordandnotflag:flag=Truecurrent.EndOfWord=Truereturnflagdefstartswith(self,prefix:str)->bool:'''Doestheprefixtreecontainentriesstartingwithaspecificprefix?'''current=self.rootforcinprefix:ifcnotincurrent.children:returnFalsecurrent=current.children[c]returnTruedefnoPrefix(words:list[str])->None:'''SayN=len(words)andL=maxwordlength.Spacecomplexity:O(NL)Timecomplexity:O(NL)'''# Write your code heretrie=Trie()forwordinwords:# Check if word exists in trie. If not, add word to trie.iftrie.startswith(word):print('BADSET',word,sep='\n')returnNone# When inserting word into trie, determine if any pre-added word in trie is a prefix of the newly added word.bool_flag=trie.insert(word)ifbool_flag:print('BADSET',word,sep='\n')returnNoneprint('GOODSET')
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
No Prefix Set
You are viewing a single comment's thread. Return to all comments →
My solution in Python 3 using trie