Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 769 Bytes

File metadata and controls

33 lines (29 loc) · 769 Bytes

Array

Screen Shot 2023-01-04 at 12 39 50 AM

One pass

/**
 * @param {string[]} wordsDict
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
var shortestDistance = function(wordsDict, word1, word2) {
    let ptr = 0;
    let i = -1;
    let j = -1;
    let distance = Infinity;

    while(ptr < wordsDict.length) {
        if(wordsDict[ptr] === word1) {
            i = ptr;
        } else if(wordsDict[ptr] === word2) {
            j = ptr;
        }

        if(i >= 0 && j >= 0) {
            distance = Math.min(distance, Math.abs(i - j));
        }
        ptr++;
    }
    return distance;
};