#676

Implement Magic Dictionary

Medium
Hash TableStringDepth-First SearchDesignTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m)Space O(n * m)

Using a Trie allows us to efficiently store the words and check for matches with a single character change. This structure helps in reducing the number of comparisons needed by leveraging the prefix nature of words.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a Trie from the list of words in the dictionary.
  2. 2Step 2: For each character in the searchWord, traverse the Trie while allowing one character to differ.
  3. 3Step 3: If we reach the end of a valid path in the Trie with exactly one character changed, return true; otherwise, return false.
solution.py33 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end = False
5
6class MagicDictionary:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def buildDict(self, dictionary):
11        for word in dictionary:
12            node = self.root
13            for char in word:
14                if char not in node.children:
15                    node.children[char] = TrieNode()
16                node = node.children[char]
17            node.is_end = True
18
19    def search(self, searchWord):
20        return self._search(self.root, searchWord, 0, False)
21
22    def _search(self, node, word, index, modified):
23        if index == len(word):
24            return modified and node.is_end
25        char = word[index]
26        for key in node.children:
27            if key == char:
28                if self._search(node.children[key], word, index + 1, modified):
29                    return True
30            elif not modified:
31                if self._search(node.children[key], word, index + 1, True):
32                    return True
33        return False

Complexity note: The time complexity is O(n * m) where n is the number of words and m is the maximum length of the words. This is because we traverse each word in the dictionary to build the Trie and then perform a search that can potentially check all characters in the Trie. The space complexity is O(n * m) due to the storage of the Trie structure.

  • 1Using a Trie can significantly reduce the number of comparisons needed.
  • 2Understanding character differences is crucial for this problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.