Implement Magic Dictionary - Problem

Design a data structure that is initialized with a list of different words. Given a string, determine if you can change exactly one character in this string to match any word in the data structure.

Implement the MagicDictionary class:

  • MagicDictionary() - Initializes the object
  • buildDict(String[] dictionary) - Sets the data structure with an array of distinct strings dictionary
  • 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

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["MagicDictionary", "buildDict", "search", "search"], inputs = [[], ["hello", "leetcode"], "hello", "hhllo"]
Output: [null, null, false, true]
💡 Note: Initialize dictionary with ["hello", "leetcode"]. Search "hello" returns false (can't change to itself). Search "hhllo" returns true (change 'h' to 'e' makes "hello")
Example 2 — Multiple Words
$ Input: operations = ["MagicDictionary", "buildDict", "search", "search"], inputs = [[], ["hello", "hallo"], "hello", "hillo"]
Output: [null, null, true, true]
💡 Note: Dictionary has ["hello", "hallo"]. Search "hello" returns true (change 'e' to 'a' makes "hallo"). Search "hillo" returns true (change 'i' to 'e' makes "hello")
Example 3 — No Match
$ Input: operations = ["MagicDictionary", "buildDict", "search"], inputs = [[], ["hello"], "hellllo"]
Output: [null, null, false]
💡 Note: Dictionary has ["hello"]. Search "hellllo" returns false (different lengths, cannot match with exactly one change)

Constraints

  • 1 ≤ dictionary.length ≤ 100
  • 1 ≤ dictionary[i].length ≤ 100
  • dictionary[i] consists of only lower-case English letters
  • All the strings in dictionary are distinct
  • 1 ≤ searchWord.length ≤ 100
  • searchWord consists of only lower-case English letters

Visualization

Tap to expand
Magic Dictionary: One Character Change CheckhelloleetcodeDictionary WordshhlloSearch WordCharacter Comparison:h ≠ h ❌h = e ✓l = l ✓l = l ✓o = o ✓Difference count: 1 (exactly what we need!)Result: truehhllo can become hello with exactly 1 character change
Understanding the Visualization
1
Input
Dictionary: ["hello", "leetcode"], Search: "hhllo"
2
Process
Check if exactly 1 character change creates a match
3
Output
Return true (hhllo → hello with 1 change)
Key Takeaway
🎯 Key Insight: Pre-processing dictionary words into patterns enables O(1) lookup per search pattern
Asked in
Google 25 Facebook 20 Amazon 15
67.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen