Python 0676.py
class MagicDictionary:
def buildDict(self, dictionary: List[str]) -> None:
self.dict = dictionary
def search(self, searchWord: str) -> bool:
for d in self.dict:
if len(d) == len(searchWord):
diff = 0
for i in range(len(d)):
if d[i] != searchWord[i]:
diff += 1
if diff > 1:
break
if diff == 1:
return True
return False
Difficulty
and has an acceptance rate of about 58% (100k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Design
- Hash Table
- String
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided MagicDictionary class implements a simple dictionary that supports building a collection of words and searching for a word that differs by exactly one character. The implementation stores the supplied list of words directly and performs a linear scan during each search, comparing each candidate word character by character. The design is straightforward, relying on Python’s dynamic typing and built-in sequence operations.
Data Structure Initialization
The buildDict method receives a list of strings and assigns it to an instance attribute. This step establishes the internal storage that the search method will later traverse.
def buildDict(self, dictionary: List[str]) -> None:
self.dict = dictionary
By keeping a reference to the original list, the class avoids copying data, which conserves memory and reduces construction time.
Search Logic
The search method iterates over every stored word, first checking length equality to filter out ineligible candidates. For each word of matching length, it counts character mismatches, exiting early if more than one mismatch is found. If exactly one mismatch is detected, the method returns True; otherwise, after exhausting all candidates, it returns False.
def search(self, searchWord: str) -> bool:
for d in self.dict:
if len(d) == len(searchWord):
diff = 0
for i in range(len(d)):
if d[i] != searchWord[i]:
diff += 1
if diff > 1:
break
if diff == 1:
return True
return False
The inner loop performs a direct index comparison, which is efficient for short strings. The early break when diff exceeds one prevents unnecessary comparisons for words that already fail the one-character-difference criterion.
Edge Cases Handled
The implementation gracefully handles several edge conditions without additional code. When the dictionary is empty, the outer loop never executes, and the method returns False, correctly indicating that no matching word exists. If the searchWord has a length that does not match any stored word, the length check filters out all entries, again resulting in False. The algorithm also correctly processes words that are identical except for a single differing character, returning True only in that precise scenario. Cases where multiple characters differ are caught by the early termination condition, ensuring they do not produce a false positive.
Performance Optimizations
A notable optimization is the length pre-filter: by comparing len(d) to len(searchWord) before entering the character-by-character loop, the code eliminates entire branches of work for words that could never satisfy the one-difference rule. This reduces the number of inner loop iterations dramatically when the dictionary contains words of varying lengths.
Another optimization is the incremental mismatch counter combined with an early exit. As soon as the counter exceeds one, the inner loop breaks, avoiding further character comparisons for that candidate. This early termination is especially beneficial when the mismatch occurs early in the word, saving the cost of scanning the remainder of the string.
Finally, the direct assignment of the input list to self.dict avoids the overhead of constructing auxiliary data structures such as hash maps or tries. While this choice trades off search speed for construction simplicity, it eliminates the memory and time costs associated with building more complex indices.
ELI5 - Simplified Explanation
Imagine a giant box filled with many different words written on little cards. The buildDict part is like taking all those cards and putting them safely into your toy chest so you can look at them later.
When it is time to use the search part, you pick one special word to look for, like a secret code. You go through every card in the chest one by one. First, you check if the size of the card matches the size of your secret code. If the sizes are the same, you hold them side by side and peek at the letters. You look for exactly one tiny spot where the letters are different. If you find a word that has all the same letters except for one, that word is a match. You keep checking until you find that one special word or until you run out of cards.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 208: Implement Trie (Prefix Tree)
- problem 720: Longest Word in Dictionary
Solved On The Same Day
- problem 621: Task Scheduler
- problem 636: Exclusive Time of Functions
- problem 677: Map Sum Pairs
- problem 1658: Minimum Operations to Reduce X to Zero
- problem 710: Random Pick with Blacklist
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality