Javascript Solution | O(n)


  • 0

    The run time isn't that great, I'll work on improving that!

    var shortestDistance = function(words, word1, word2) {
        var finalDistance = 0;
        if (words) {
            var p = null;
            var q = null;
            finalDistance = 10000;
            var cd = 0;
    
            for (var i = 0; i < words.length; i++) {
    
                if (words[i] === word1) {
                    p = i
                } else if (words[i] === word2) {
                    q = i;
                }
    
                if (p !== null && q !== null) {
                    cd = Math.abs(p - q);
                    finalDistance = Math.min(finalDistance, cd);
                }
            }
        }
        return finalDistance;
    };
    

Log in to reply
 

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