Iam_Sandeep

Shortest Unique prefix for every word

Jun 15th, 2022 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. class Solution:
  2.     def findPrefixes(self, arr, N):
  3.     '''
  4.    while adding each character to trie
  5.    If character is not present then create a new dictionary for that character with also an item (freq:1) and get into it.
  6.    
  7.    If character is already prsent in the current dictionary
  8.    then increase the count of that branch i.e. freq which represents the no of words passing through
  9.    that character.
  10.    
  11.    '''
  12.         def add(word):
  13.             cur=root
  14.             for w in word:
  15.                 if w in cur:
  16.                     cur[w]['freq']+=1
  17.                 else:
  18.                     cur[w]={'freq':1}
  19.                 cur=cur[w]
  20.             cur['*']=True
  21.         '''
  22.        Now traverse each character of word through trie.
  23.        First add character to ans and check whether the frequency of that character==1 .If so return ans
  24.        else Traverse
  25.        '''
  26.         def find(word):
  27.             ans=''
  28.             cur=root
  29.             for w in word:
  30.                 ans=ans+w
  31.                 if cur[w]['freq']==1:
  32.                     return ans
  33.                 cur=cur[w]
  34.         ans=[]
  35.         root={}
  36.         for word in arr:
  37.             add(word)
  38.         for word in arr:
  39.             ans.append(find(word))
  40.         return ans
Add Comment
Please, Sign In to add comment