Implement Magic Dictionary

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a data structure that is initialized with a list of different words. You are given a string and need to 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(dictionary) — Sets the data structure with an array of distinct strings dictionary.
  • search(searchWord) — Returns true if you can change exactly one character in searchWord to match a string in the dictionary, otherwise returns false.

Examples

Example 1:

Input: operations = ["MagicDictionary","buildDict","search","search","search","search"], operands = [[],[["hello","leetcode"]],["hello"],["hhllo"],["hell"],["leetcoded"]]

Output: [null,null,false,true,false,false]

Explanation: The dictionary is built with ["hello", "leetcode"]. Searching "hello" returns false because changing one character cannot yield a different dictionary match. Searching "hhllo" returns true because changing 'h' to 'e' at index 1 yields "hello". Searching "hell" returns false (different length). Searching "leetcoded" returns false (different length).

Example 2:

Input: operations = ["MagicDictionary","buildDict","search","search","search"], operands = [[],[["a","b","ab"]],["a"],["c"],["ab"]]

Output: [null,null,true,true,false]

Explanation: Searching "a" returns true because changing 'a' to 'b' yields "b". Searching "c" returns true because changing 'c' to 'a' yields "a". Searching "ab" returns false because no single character change yields another word of length 2.

Constraints

  • 1 <= dictionary.length <= 100
  • 1 <= dictionary[i].length <= 100
  • dictionary[i] consists of only lowercase English letters
  • All strings in dictionary are distinct
  • 1 <= searchWord.length <= 100
  • searchWord consists of only lowercase English letters
  • At most 100 calls will be made to search
Source: Trie pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle