10 lines JavaScript solution with no nested condition checks

  • 1

    Keep p1 as the current index of word and p2 as the previous index of word if word1 equals word2

    function shortestWordDistance(words, word1, word2) {
    	var diff = words.length, p1 = -words.length, p2 = words.length;
    	words.forEach((v, i) => {
    		if (v === word1 && v === word2) [p1, p2] = [i, p1];
    		else if (v === word1) p1 = i;
    		else if (v === word2) p2 = i;
    		diff = Math.min(diff, Math.abs(p1 - p2));
    	return diff;

Log in to reply

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