Implement Magic Dictionary Problem
Description
LeetCode Problem 676.
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement theMagicDictionaryclass:
- MagicDictionary()Initializes the object.
- void buildDict(String[]dictionary)Sets the data structurewith an array of distinct strings dictionary.
- bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.
Example 1:
Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();
magicDictionary.buildDict(["hello", "leetcode"]);
magicDictionary.search("hello"); // return False
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
magicDictionary.search("hell"); // return False
magicDictionary.search("leetcoded"); // return False
Constraints:
- 1 <=dictionary.length <= 100
- 1 <=dictionary[i].length <= 100
- dictionary[i] consists of only lower-case English letters.
- All the strings indictionaryare distinct.
- 1 <=searchWord.length <= 100
- searchWordconsists of only lower-case English letters.
- buildDictwill be called only once before search.
- At most 100 calls will be made to search.
Solution
Approach: Wildcard Patterns
Two words of the same length differ in exactly one position i when they become equal after replacing position i with a wildcard. For example, "hello" and "hhllo" both turn into "h*llo". So instead of comparing searchWord with every word, we precompute these patterns.
- buildDict: for every word and every position
i, form the patternword[:i] + "*" + word[i+1:]and count how many dictionary words produce it. Also keep the words in a set. - search: form the same patterns for
searchWord. A pattern with a count means some dictionary word agrees withsearchWordeverywhere except at positioni.
The detail to get right is that we must change exactly one character, so the word searchWord itself does not count as a match (Example 1: search("hello") is false). For one pattern:
- If its count is greater than 1, at least one of those words is not
searchWord(the words are distinct), and that word differs from it exactly ati. Returntrue. - If its count is 1, it is a match only when
searchWordis not in the dictionary, because otherwise that one word issearchWorditself.
Words of a different length never share a pattern, so "hell" does not match "hello".
Complexity: buildDict takes O(L2) time per word and search takes O(L2) time, where L is the word's length, since we build L patterns of length L. The patterns use O(N · L2) space for N dictionary words.
import collections
class MagicDictionary:
def __init__(self):
self.words = set()
# "h*llo" -> how many dictionary words fit this pattern
self.pattern_count = collections.Counter()
def buildDict(self, dictionary: List[str]) -> None:
for word in dictionary:
self.words.add(word)
for pattern in self._patterns(word):
self.pattern_count[pattern] += 1
def search(self, searchWord: str) -> bool:
for pattern in self._patterns(searchWord):
count = self.pattern_count[pattern]
# A match must differ from searchWord, so searchWord itself does not count.
if count > 1 or (count == 1 and searchWord not in self.words):
return True
return False
def _patterns(self, word: str) -> List[str]:
"""word with one position replaced by '*', for every position."""
return [word[:i] + "*" + word[i + 1:] for i in range(len(word))]
Now write it from memory
Close the write-up and solve it yourself against the tests.