Problem 676

Abstract / Summary

Implement a dictionary that can search for words where only one character differs from a given word.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 553 bytes | submitted September 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 58% (100k+ submissions).

Typical patterns to solve this problem:
  • Depth First Search
  • Design
  • Hash Table
  • String
  • Trie
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.00 | σ = 1.24

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
34 links | 20 authors | 8 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

4 medium 1 hard
6 solutions   September 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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