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 objectbuildDict(String[] dictionary)- Sets the data structure with an array of distinct strings dictionarysearch(String searchWord)- Returnstrueif you can change exactly one character in searchWord to match any string in the data structure, otherwise returnsfalse
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code