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.
This problem is annoying because it is solution dependent and doing the most basic solution using sets/dicts is too slow to pass all the test cases. Any implementation of a Trie data structure will pass all tests though. Here is mine after some help cleaning up from our AI overlords:
classTrieNode:def__init__(self):self.seen:dict[str,TrieNode]={}self.word_end=False# Adds a node beneath the current node and returns itdefadd_node(self,character:str)->Self:new_node=TrieNode()self.seen[character]=new_nodereturnnew_node# Returns a node if it exists beneath this node, otherwise Nonedefget_node(self,character:str)->Self|None:returnself.seen.get(character)classTrie:def__init__(self):self.nodes:dict[str,TrieNode]={}defadd_string(self,string:str):# Get the root node of this stringc_1=string[0]parent=self.nodes.get(string[0])# If it doesn't exist, create itifnotparent:parent=TrieNode()self.nodes[c_1]=parent# Start at the parent, loop through the rest of the charactersforiinrange(1,len(string)):c_i=string[i]child_node=parent.get_node(c_i)# If a child node exists with this character, traverse to itifchild_node:parent=child_node# Otherwise, we need to create itelse:parent=parent.add_node(c_i)# Once we reach the end of the word, mark the final parent as the end of a wordparent.word_end=Truedefsearch_string(self,string:str)->bool:# Get the root node of this stringroot=self.nodes.get(string[0])# If there is no root node matching this string, return no matchifnotroot:returnFalse# If the string is only 1 character long or our root is a complete wordifroot.word_endorlen(string)==1:returnTrue# Start at the root, loop through the rest of the charactersparent=rootforiinrange(1,len(string)):# Get the next node in the treeparent=parent.get_node(string[i])# If there is no next node, then no prefix match existsifnotparent:returnFalse# If there is a next node and:# 1. If parent is a complete word, it is a prefix of our string# 3. If we have reached the end of our string, then it itself is a prefix of a seen wordifparent.word_endori==len(string)-1:returnTruedefnoPrefix(words):tree=Trie()forwordinwords:found=tree.search_string(word)iffound:print("BAD SET")print(word)returnelse:tree.add_string(word)print("GOOD SET")
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 →
This problem is annoying because it is solution dependent and doing the most basic solution using sets/dicts is too slow to pass all the test cases. Any implementation of a Trie data structure will pass all tests though. Here is mine after some help cleaning up from our AI overlords: