Skip to main content
Back to problems
#676
Medium Algorithms

Implement magic dictionary

Hash Table String Depth-First Search Design Trie
57.7% acceptance
Feb 20, 2026
1466
215
MagicDictionary: search returns true if exactly one character change matches any word in the dictionary.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
struct MagicDictionary {
  words: Vec<String>,
}

impl MagicDictionary {
  fn new() -> Self {
    MagicDictionary { words: Vec::new() }
  }

  fn build_dict(&mut self, dictionary: Vec<String>) {
    self.words = dictionary;
  }

  fn search(&self, search_word: String) -> bool {
    let sw = search_word.as_bytes();
    for word in &self.words {
      let wb = word.as_bytes();
      if wb.len() == sw.len() {
        let diffs = wb.iter().zip(sw.iter()).filter(|(a, b)| a != b).count();
        if diffs == 1 {
          return true;
        }
      }
    }
    false
  }
}