Javascript beasts 80%


  • 0
    M

    var shortestDistance = function(words, word1, word2) {

    //one pass, one index, time: O(N), space:O(1)
    var index = -1, ans = Number.MAX_SAFE_INTEGER;
    for (var i = 0; i < words.length; i++) {
        if (words[i] === word1 || words[i] === word2) {
            if (index !== -1 && words[index] !== words[i]) {
                ans = Math.min(i - index, ans);
            }
            index = i;
        }
    }
    return ans;
    

    };


Log in to reply
 

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