KatInterview

288. Unique Word Abbreviation

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

The core of the problem is to check if a given word's abbreviation is "unique" with respect to a dictionary. The definition of uniqueness is specific and has two parts:

Solution

Unique Word Abbreviation in Python

class ValidWordAbbr:

    def __init__(self, dictionary: List[str]):
        # Map from abbreviation to a set of words having that abbreviation.
        self.abbr_map = {}
        # Pre-process the dictionary.
        for word in dictionary:
            abbr = self._get_abbr(word)
            if abbr not in self.abbr_map:
                self.abbr_map[abbr] = set()
            self.abbr_map[abbr].add(word)

    def isUnique(self, word: str) -> bool:
        abbr = self._get_abbr(word)
        
        # Condition 1: No word in the dictionary has this abbreviation.
        if abbr not in self.abbr_map:
            return True
        
        # Condition 2: All words in the dictionary with this abbreviation are the same as 'word'.
        # This means the set of words for this abbreviation should contain only 'word'.
        word_set = self.abbr_map[abbr]
        return len(word_set) == 1 and word in word_set

    # Helper function to generate the abbreviation for a word.
    def _get_abbr(self, word: str) -> str:
        if len(word) <= 2:
            return word
        return f"{word[0]}{len(word) - 2}{word[-1]}"


# Your ValidWordAbbr object will be instantiated and called as such:
# obj = ValidWordAbbr(dictionary)
# param_1 = obj.isUnique(word)

Unique Word Abbreviation in Java

class ValidWordAbbr {
    // Map from abbreviation to a set of words having that abbreviation.
    private Map<String, Set<String>> abbrMap;

    // Helper function to generate the abbreviation for a word.
    private String getAbbr(String word) {
        if (word.length() <= 2) {
            return word;
        }
        return word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1);
    }

    public ValidWordAbbr(String[] dictionary) {
        abbrMap = new HashMap<>();
        // Pre-process the dictionary.
        for (String word : dictionary) {
            String abbr = getAbbr(word);
            // Get the set for the abbreviation, creating it if it doesn't exist.
            abbrMap.putIfAbsent(abbr, new HashSet<>());
            // Add the word to the set.
            abbrMap.get(abbr).add(word);
        }
    }
    
    public boolean isUnique(String word) {
        String abbr = getAbbr(word);
        Set<String> wordSet = abbrMap.get(abbr);

        // Condition 1: No word in the dictionary has this abbreviation.
        if (wordSet == null) {
            return true;
        }
        
        // Condition 2: All words in the dictionary with this abbreviation are the same as 'word'.
        // This means the set should contain only 'word'.
        return wordSet.size() == 1 && wordSet.contains(word);
    }
}

/**
 * Your ValidWordAbbr object will be instantiated and called as such:
 * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
 * boolean param_1 = obj.isUnique(word);
 */

Unique Word Abbreviation in C++

class ValidWordAbbr {
private:
    // Map from abbreviation to a set of words having that abbreviation.
    std::unordered_map<std::string, std::unordered_set<std::string>> abbrMap;

    // Helper function to generate the abbreviation for a word.
    std::string getAbbr(const std::string& word) {
        if (word.length() <= 2) {
            return word;
        }
        return word.front() + std::to_string(word.length() - 2) + word.back();
    }

public:
    ValidWordAbbr(vector<string>& dictionary) {
        // Pre-process the dictionary.
        for (const std::string& word : dictionary) {
            std::string abbr = getAbbr(word);
            // Insert the word into the set for the corresponding abbreviation.
            abbrMap[abbr].insert(word);
        }
    }
    
    bool isUnique(string word) {
        std::string abbr = getAbbr(word);
        
        // Check if no word in the dictionary has this abbreviation.
        auto it = abbrMap.find(abbr);
        if (it == abbrMap.end()) {
            return true;
        }
        
        // If there are words with this abbreviation, check if they are all
        // identical to the given 'word'. This means the set of words for this
        // abbreviation should contain only 'word'.
        const auto& wordSet = it->second;
        return wordSet.size() == 1 && wordSet.count(word) == 1;
    }
};

/**
 * Your ValidWordAbbr object will be instantiated and called as such:
 * ValidWordAbbr* obj = new ValidWordAbbr(dictionary);
 * bool param_1 = obj->isUnique(word);
 */

Unique Word Abbreviation in TypeScript

class ValidWordAbbr {
    // Map from abbreviation to a set of words having that abbreviation.
    private abbrMap: Map<string, Set<string>>;

    constructor(dictionary: string[]) {
        this.abbrMap = new Map<string, Set<string>>();
        // Pre-process the dictionary.
        for (const word of dictionary) {
            const abbr = this.getAbbr(word);
            // Get the set for the abbreviation, creating it if it doesn't exist.
            if (!this.abbrMap.has(abbr)) {
                this.abbrMap.set(abbr, new Set<string>());
            }
            // Add the word to the set. The '!' asserts that the value is not undefined.
            this.abbrMap.get(abbr)!.add(word);
        }
    }

    isUnique(word: string): boolean {
        const abbr = this.getAbbr(word);
        const wordSet = this.abbrMap.get(abbr);

        // Condition 1: No word in the dictionary has this abbreviation.
        if (!wordSet) {
            return true;
        }

        // Condition 2: All words in the dictionary with this abbreviation are the same as 'word'.
        // This means the set should contain only 'word'.
        return wordSet.size === 1 && wordSet.has(word);
    }

    // Helper function to generate the abbreviation for a word.
    private getAbbr(word: string): string {
        if (word.length <= 2) {
            return word;
        }
        return `${word[0]}${word.length - 2}${word[word.length - 1]}`;
    }
}

/**
 * Your ValidWordAbbr object will be instantiated and called as such:
 * var obj = new ValidWordAbbr(dictionary)
 * var param_1 = obj.isUnique(word)
 */

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.