KatInterview

676. Implement Magic Dictionary

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Pre-computation with Generalized Words

This problem asks us to determine if a given searchWord can be transformed into a word from a pre-defined dictionary by changing exactly one character.

Solution

Implement Magic Dictionary in Python

from collections import defaultdict

class MagicDictionary:

    def __init__(self):
        # Initialize a defaultdict to store generalized words and their corresponding original words.
        self._lookup = defaultdict(list)
        
    def buildDict(self, dictionary: list[str]) -> None:
        # Iterate through each word in the dictionary
        for word in dictionary:
            # For each word, generate all possible generalized forms
            for i in range(len(word)):
                # Create a generalized key by replacing one character with a wildcard '*'
                key = word[:i] + '*' + word[i+1:]
                # Map the generalized key to the original word
                self._lookup[key].append(word)

    def search(self, searchWord: str) -> bool:
        # For the searchWord, generate its generalized forms
        for i in range(len(searchWord)):
            key = searchWord[:i] + '*' + searchWord[i+1:]
            
            # Check if this generalized key exists in our lookup map
            if key in self._lookup:
                # Get the list of candidate words from the dictionary
                candidates = self._lookup[key]
                # If there's more than one candidate, it's a guaranteed match.
                # e.g., dict has 'bill', 'ball'. search for 'bull'. key 'b*ll' has ['bill', 'ball'].
                # If searchWord is 'bill', we can change to 'ball'.
                if len(candidates) > 1:
                    return True
                # If there's one candidate, it's a match if it's not the searchWord itself.
                # This handles cases like search('hello') when 'hello' is in the dictionary.
                if len(candidates) == 1 and candidates[0] != searchWord:
                    return True
                    
        # If no match is found after checking all positions, return false
        return False

Implement Magic Dictionary in Java

class MagicDictionary {

    private Map<String, List<String>> lookup;

    public MagicDictionary() {
        lookup = new HashMap<>();
    }
    
    public void buildDict(String[] dictionary) {
        // Iterate through each word in the dictionary
        for (String word : dictionary) {
            char[] chars = word.toCharArray();
            // For each word, generate all possible generalized forms
            for (int i = 0; i < chars.length; i++) {
                char originalChar = chars[i];
                // Create a generalized key by replacing one character with a wildcard '*'
                chars[i] = '*';
                String key = new String(chars);
                // Restore the original character
                chars[i] = originalChar;
                
                // Map the generalized key to the original word
                lookup.computeIfAbsent(key, k -> new ArrayList<>()).add(word);
            }
        }
    }
    
    public boolean search(String searchWord) {
        char[] chars = searchWord.toCharArray();
        // For the searchWord, generate its generalized forms
        for (int i = 0; i < chars.length; i++) {
            char originalChar = chars[i];
            chars[i] = '*';
            String key = new String(chars);
            chars[i] = originalChar;
            
            // Check if this generalized key exists in our lookup map
            if (lookup.containsKey(key)) {
                // Get the list of candidate words from the dictionary
                List<String> candidates = lookup.get(key);
                // If there's more than one candidate, it's a guaranteed match.
                if (candidates.size() > 1) {
                    return true;
                }
                // If there's one candidate, it's a match if it's not the searchWord itself.
                if (candidates.size() == 1 && !candidates.get(0).equals(searchWord)) {
                    return true;
                }
            }
        }
        // If no match is found after checking all positions, return false
        return false;
    }
}

Implement Magic Dictionary in C++

class MagicDictionary {
private:
    unordered_map<string, vector<string>> lookup;

public:
    MagicDictionary() {
    }
    
    void buildDict(vector<string> dictionary) {
        // Iterate through each word in the dictionary
        for (const string& word : dictionary) {
            // For each word, generate all possible generalized forms
            for (int i = 0; i < word.length(); ++i) {
                // Create a generalized key by replacing one character with a wildcard '*'
                string key = word.substr(0, i) + '*' + word.substr(i + 1);
                // Map the generalized key to the original word
                lookup[key].push_back(word);
            }
        }
    }
    
    bool search(string searchWord) {
        // For the searchWord, generate its generalized forms
        for (int i = 0; i < searchWord.length(); ++i) {
            string key = searchWord.substr(0, i) + '*' + searchWord.substr(i + 1);
            
            // Check if this generalized key exists in our lookup map
            if (lookup.count(key)) {
                // Get the list of candidate words from the dictionary
                vector<string>& candidates = lookup[key];
                // If there's more than one candidate, it's a guaranteed match.
                // e.g., dict has 'bill', 'ball'. search for 'bull'. key 'b*ll' has ['bill', 'ball'].
                if (candidates.size() > 1) {
                    return true;
                }
                // If there's one candidate, it's a match if it's not the searchWord itself.
                // This handles cases like search('hello') when 'hello' is in the dictionary.
                if (candidates.size() == 1 && candidates[0] != searchWord) {
                    return true;
                }
            }
        }
        // If no match is found after checking all positions, return false
        return false;
    }
};

Implement Magic Dictionary in TypeScript

class MagicDictionary {
    private lookup: Map<string, string[]>;

    constructor() {
        this.lookup = new Map<string, string[]>();
    }

    buildDict(dictionary: string[]): void {
        // Iterate through each word in the dictionary
        for (const word of dictionary) {
            // For each word, generate all possible generalized forms
            for (let i = 0; i < word.length; i++) {
                // Create a generalized key by replacing one character with a wildcard '*'
                const key = word.substring(0, i) + '*' + word.substring(i + 1);
                
                // Map the generalized key to the original word
                if (!this.lookup.has(key)) {
                    this.lookup.set(key, []);
                }
                this.lookup.get(key)!.push(word);
            }
        }
    }

    search(searchWord: string): boolean {
        // For the searchWord, generate its generalized forms
        for (let i = 0; i < searchWord.length; i++) {
            const key = searchWord.substring(0, i) + '*' + searchWord.substring(i + 1);
            
            // Check if this generalized key exists in our lookup map
            if (this.lookup.has(key)) {
                // Get the list of candidate words from the dictionary
                const candidates = this.lookup.get(key)!;
                // If there's more than one candidate, it's a guaranteed match.
                if (candidates.length > 1) {
                    return true;
                }
                // If there's one candidate, it's a match if it's not the searchWord itself.
                if (candidates.length === 1 && candidates[0] !== searchWord) {
                    return true;
                }
            }
        }
        // If no match is found after checking all positions, return false
        return false;
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.