JavaScript solution amortized O(n) time


  • 0
    W

    This solution uses a hash dictionary and a Set for word storage. Complexity should be O(n) time where n is the number of times isUnique is executed

    var ValidWordAbbr = function(dictionary) {
        this.dictionary = {};
        for (let word of dictionary) {
            let abbr = `${word[0]}${word.length-2}${word[word.length-1]}`;
            if (!this.dictionary[abbr]) this.dictionary[abbr] = new Set();
            this.dictionary[abbr].add(word);
        }
    };
    
    ValidWordAbbr.prototype.isUnique = function(word) {
        let abbr = `${word[0]}${word.length-2}${word[word.length-1]}`;
        if (!this.dictionary[abbr]) return true;
        if (this.dictionary[abbr].has(word) && this.dictionary[abbr].size == 1) return true;
        return false;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.