Javascript Solution | 145ms


  • 0

    I think I can forego of the two for loops and use the sort method that others are employing, but this is what came to mind first. So here goes!

    var WordDistance = function(words) {
        // Store the words array
        this.words = words;
        this.hash = {};
    
        // Create a hash map of all words, where each word maps to it's index
        for (var i = 0; i < words.length; i++) {
            if (!this.hash[words[i]]) {
                this.hash[words[i]] = [];
            }
            this.hash[words[i]].push(i);
        }
    };
    
    /** 
     * @param {string} word1 
     * @param {string} word2
     * @return {number}
     */
    WordDistance.prototype.shortest = function(word1, word2) {
        if (this.words) {
            // Case where there's just one index stored for both words.
            // No need to parse all values
            if (this.hash[word1].length == 1 && this.hash[word2].length == 1) {
                return Math.abs(this.hash[word1][0] - this.hash[word2][0]);
            } else {
                var currentMin = Infinity;
                for (var i = 0; i < this.hash[word1].length; i++) {
                    for (var j = 0; j < this.hash[word2].length; j++) {
                        currentMin = Math.min(currentMin, Math.abs(this.hash[word1][i] - this.hash[word2][j]));
                    }
                }
            }
            return currentMin === Infinity ? null : currentMin;
        }
    };
    

Log in to reply
 

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