MediumNo. 0676

Implement Magic Dictionary — LeetCode 676 Python Solution

Pattern
Trie
Topics
Depth-First Search, Design, Trie, Hash Table, String
Reading time
8 min

The problem

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.

Example

Input
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
Output
[null, null, false, true, false, false]
Explanation
MagicDictionary magicDictionary = new MagicDictionary();

Python solution

PythonSolution
class Trie:
    __slots__ = "children", "is_end"

    def __init__(self):
        self.children: List[Optional[Trie]] = [None] * 26
        self.is_end = False

    def insert(self, w: str) -> None:
        node = self
        for c in w:
            idx = ord(c) - ord("a")
            if node.children[idx] is None:
                node.children[idx] = Trie()
            node = node.children[idx]
        node.is_end = True

    def search(self, w: str) -> bool:
        def dfs(i: int, node: Optional[Trie], diff: int) -> bool:
            if i == len(w):
                return diff == 1 and node.is_end
            j = ord(w[i]) - ord("a")
            if node.children[j] and dfs(i + 1, node.children[j], diff):
                return True
            return diff == 0 and any(
                node.children[k] and dfs(i + 1, node.children[k], 1)
                for k in range(26)
                if k != j
            )

        return dfs(0, self, 0)


class MagicDictionary:
    def __init__(self):
        self.trie = Trie()

    def buildDict(self, dictionary: List[str]) -> None:
        for w in dictionary:
            self.trie.insert(w)

    def search(self, searchWord: str) -> bool:
        return self.trie.search(searchWord)


# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)

Complexity

Time
O(n × l + q × l × |Σ|)
Space · auxiliary
O(n × l), where n and l are the number of words in the dictionary and the average length of the words, respectively, and q is the number of words searched

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 676. Implement Magic Dictionary is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0677Map Sum PairsMedium
0208Implement Trie (Prefix Tree)Medium
0745Prefix and Suffix SearchHard
2227Encrypt and Decrypt StringsHard
0139Word BreakMedium
0140Word Break IIHard

Frequently asked questions

How hard is LeetCode 676. Implement Magic Dictionary?

LeetCode 676. Implement Magic Dictionary is rated Medium on LeetCode.

What is the time complexity of LeetCode 676. Implement Magic Dictionary?

The Python solution on this page runs in O(n × l + q × l × |Σ|).

What is the space complexity of LeetCode 676. Implement Magic Dictionary?

The Python solution on this page uses O(n × l), where n and l are the number of words in the dictionary and the average length of the words, respectively, and q is the number of words searched auxiliary space.

What topics does LeetCode 676. Implement Magic Dictionary cover?

LeetCode 676. Implement Magic Dictionary is tagged Depth-First Search, Design, Trie, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.