Implement a magic directory with buildDict, and search methods.



For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.



For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.


Example 1:

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False



Note:

You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

Difficulty: interview

Starter code:

class MagicDictionary:
    def __init__(self):
        """
        Initialize your data structure here.
        """
    def buildDict(self, dictionary: List[str]) -> None:
    def search(self, searchWord: str) -> bool:
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)

Solutions:
class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.l = []
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         self.l= dict
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         def diffnumber(a,b):
             count = 0
             for i in range(len(a)):
                 if a[i] !=b[i]:
                     count +=1
             return count
         for x in self.l:
             if len(x) == len(word) and diffnumber(x,word) ==1:
                 return True
         return False
                 
                 
         
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.dict1 = {}
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for i in dict:
             self.dict1[len(i)] = self.dict1.get(len(i),[]) + [i]
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         for i in self.dict1.get(len(word),[]):
             count = 0
             for j in range(len(word)):
                 if i[j] != word[j]:
                     count  += 1
             if count == 1:
                 return True
         return False
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         # use a hash to store len(word) => list of workds
         # then in search only need to search those that are the same length
         self.hsh = collections.defaultdict(list)
         
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in dict:
             self.hsh[len(word)].append(word)
         
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         return any(sum(x != y for x, y in zip(word, candidate)) == 1 for candidate in self.hsh[len(word)])
         
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.tier=[None]*27
         
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in dict:
             p=self.tier
             for c in word:
                 t=ord(c)-ord('a')
                 if not p[t]:
                     p[t]=[None]*27
                 p=p[t]
             p[26]=1
         
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         def func(w):
             p=self.tier
             for c in w:
                 t=ord(c)-ord('a')
                 if not p[t]:
                     return False
                 p=p[t]
             return p[26]==1
         pool='abcdefghijklmnopqrstuvwxyz'
         for i in range(len(word)):
             for cc in pool:
                 if cc!=word[i]:
                     tt=word[:i]+'%c'%cc+word[i+1:]
                     if func(tt):
                         return True
         return False
             
         
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         self.l = dict
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         n = len(word)
         for wo in self.l:
             if len(wo)==n and wo!=word:
                 for i in range(n):
                     if wo[:i]+wo[i+1:]==word[:i]+word[i+1:]:
                         return True
         return False
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


from collections import defaultdict
 
 class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.magic_dict = defaultdict(list)
 
     def buildDict(self, words):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in words:
             for i in range(len(word)):
                 self.magic_dict[word[:i] + '*' + word[i+1:]].append(word[i])
 
     def search(self, word):
         for i, char in enumerate(word):
             candidates = self.magic_dict[word[:i] + '*' + word[i+1:]]
             for origin in candidates:
                 if origin != char:
                     return True
         return False
         
         
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)

class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.word_set = {}
         self.word_origin = set([])
     def candidate(self,word):
         result = []
         for i in range(len(word)):
             result.append(word[0:i]+'*'+word[i+1:])
         return result
     
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         self.word_set = {}
         self.word_origin = set(dict)
         for item in dict:
             for cand in self.candidate(item):
                 self.word_set[cand] = self.word_set.get(cand,0)+1
                 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         for cand in self.candidate(word):
             if (self.word_set.get(cand,0) > 1 or (self.word_set.get(cand,0)==1 and word not in self.word_origin)):
                 return True
         return False
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.trie_root = dict()
         self.original_words = None
         
 
     def buildDict(self, dictionary):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         
         def add_word(trie_root, word):
             p = trie_root
             
             for character in word:
                 if character not in p:
                     p[character] = dict()
                 p = p[character]
             
             p['\0'] = True
         
         
         #for word in dictionary:
         #    add_word(self.trie_root, word)
         self.original_words = set(dictionary)
             
         
         
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         
         """
         active_tries = list()
         active_tries.append(self.trie_root)
         is_tolerable = True
         
         for character in word:
             next_active_tries = list()
             for trie in active_tries:
                 if character in trie:
                     next_active_tries.append(trie[character])
                 if character not in trie:
                     if is_tolerable:
                         is_tolerable = False
                         for c, next_trie in trie.items():
                             if c != '\0':
                                 next_active_tries.append(next_trie)
             active_tries = next_active_tries
             if not active_tries:
                 break
         
         return any('\0' in trie for trie in active_tries) and not is_tolerable
         """
         
         charset = "abcdefghijklmnopqrstuvwxyz"
         
         for index, character in enumerate(word):
             for replaced_character in charset:
                 if character != replaced_character:
                     if word[:index] + replaced_character + word[index + 1:] in self.original_words:
                         return True
         
         return False
                 
         
         
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.d = None
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         d=set()
         for word in dict:
             d.add(word)
         self.d = d
         
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         if not word:
             return
         
         def editDistDP(s1, s2):
             m, n = len(s1), len(s2)
             dp = [[0 for x in range(n+1)] for x in range(m+1)]
             for i in range(m+1):
                 for j in range(n+1):
                     if i == 0:
                         dp[i][j] = j    # Min. operations = j
                     elif j == 0:
                         dp[i][j] = i    # Min. operations = i
                     # If last characters are same, ignore last char
                     # and recur for remaining string
                     elif s1[i-1] == s2[j-1]:
                         dp[i][j] = dp[i-1][j-1]
                         # If last character are different, consider all
                     # possibilities and find minimum
                     else:
                         dp[i][j] = 1 + dp[i-1][j-1]
             return dp[m][n]
         # print(self.d)
         ans = False
         for dic in self.d:
             if len(dic) != len(word):
                 continue
             ans = ans or editDistDP(dic, word)==1
         return ans
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.dict = set()
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in dict:
             self.dict.add(word)
         
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         letters = string.ascii_lowercase
         for i in range(len(word)):
             for letter in letters:
                 if letter != word[i]:
                     if word[:i] + letter + word[i+1:] in self.dict:
                         return True
         return False
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.magic_dict = set()
 
     def buildDict(self, words):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in words:
             for i in range(len(word)):
                 for char in range(26):
                     char = chr(ord('a') + char)
                     if char != word[i]:
                         self.magic_dict.add(word[:i] + char + word[i + 1:])
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         return word in self.magic_dict
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)


"""
 Your MagicDictionary object will be instantiated and called as such:
 obj = MagicDictionary()
 obj.buildDict(dict)
 param_2 = obj.search(word)
 """
 
 
 class MagicDictionary:
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.words = collections.defaultdict(set)
 
     def buildDict(self, words):
         """
         Build a dictionary through a list of words
         :type words: List[str]
         :rtype: void
         """
         for word in words:
             for i in range(len(word)):
                 key = '{0},{1}'.format(word[:i], word[i + 1:])
                 
                 if key not in self.words:
                     self.words[key] = set()
                 
                 # add char to distinct word if its same
                 self.words[key].add(word[i])
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         for i in range(len(word)):
             key = '{0},{1}'.format(word[:i], word[i + 1:])
             
             if key not in self.words:
                 continue
             
             words = self.words[key]
             
             # 1. word[i] not in words => means not same word
             # 2. len(words) > 1 => if got same but still can mapping other
             if word[i] not in words or len(words) > 1:
                 return True
         
         return False

class Trie():
     def __init__(self):
         self.mark = list()
         self.children = {}
 
 class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.root = Trie()
         
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         node = self.root
         for word in dict:
             words = {}
             for i in range(len(word)):
                 words[word[:i] + "_" + word[i+1:]] = word[i]
             for word in words:
                 node = self.root
                 for c in word:
                     node = node.children.setdefault(c,Trie()) 
                 node.mark.append(words[word])
         
         
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         words = dict()
         for i in range(len(word)):
             words[word[:i] + "_" + word[i+1:]] = word[i]
         for word in words:
             node = self.root
             for c in word:
                 node = node.children.get(c) 
                 if not node:
                     break
             else:
                 if node.mark != list() and [words[word]] != node.mark:
                     return True
         return False
         
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)

class MagicDictionary:
 
     def __init__(self):
         """
         Initialize your data structure here.
         """
         self.dict = collections.defaultdict(list)
 
     def buildDict(self, dict):
         """
         Build a dictionary through a list of words
         :type dict: List[str]
         :rtype: void
         """
         for word in dict:
             self.dict[len(word)].append(word)
 
     def search(self, word):
         """
         Returns if there is any word in the trie that equals to the given word after modifying exactly one character
         :type word: str
         :rtype: bool
         """
         n = len(word)
         print((word, self.dict[n]))
         for item in self.dict[n]:
             count = 0
             for i in range(n):
                 if count > 1: continue
                 if item[i] != word[i]: count += 1
             if count == 1:
                 return True
         return False
                     
         
 
 
 # Your MagicDictionary object will be instantiated and called as such:
 # obj = MagicDictionary()
 # obj.buildDict(dict)
 # param_2 = obj.search(word)