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.
Working Python recursive OOP implementation of Trie.
Storing the size rather than computing recursively is essential to pass the tests.
classPrefixTree():def__init__(self,is_end=False):self.d=dict()self.is_end=is_endself.size=0# Recursively add character by characterdefadd(self,word):# Base case: empty or existing wordiflen(word)==0orself.find(word):return-1ifword[0]notinself.d.keys():self.d[word[0]]=PrefixTree()# Base case: one character wordiflen(word)==1:self.d[word[0]].is_end=True# Recursive case: add the remaining characterselse:self.d[word[0]].add(word[1:])# Caching the size is the key to good runtime in 'find()'self.size+=1# Returns number of matches for a prefixdeffind(self,prefix):# Base case: we're at the end node of the prefixiflen(prefix)==0:returnself.size+(1ifself.is_endelse0)# Base case: we can't reach the next characterifprefix[0]notinself.d.keys():return0# Recursive case: keep lookingreturnself.d[prefix[0]].find(prefix[1:])
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tries: Contacts
You are viewing a single comment's thread. Return to all comments →
Working Python recursive OOP implementation of Trie. Storing the size rather than computing recursively is essential to pass the tests.