Shortest Word Distance

easy array two pointers

Problem

Given a list of words and two distinct words word1 and word2, return the shortest distance between these two words in the list.

InputwordsDict = ["practice","makes","perfect","coding","makes"], word1 = "coding", word2 = "practice"
Output3
indices: coding=3, practice=0 → |3−0| = 3.

def shortest_distance(words, w1, w2):
    i1 = i2 = -1
    best = len(words)
    for i, w in enumerate(words):
        if w == w1: i1 = i
        elif w == w2: i2 = i
        if i1 != -1 and i2 != -1:
            best = min(best, abs(i1 - i2))
    return best
function shortestDistance(words, w1, w2) {
  let i1 = -1, i2 = -1, best = words.length;
  for (let i = 0; i < words.length; i++) {
    if (words[i] === w1) i1 = i;
    else if (words[i] === w2) i2 = i;
    if (i1 !== -1 && i2 !== -1) best = Math.min(best, Math.abs(i1 - i2));
  }
  return best;
}
class Solution {
    public int shortestDistance(String[] words, String w1, String w2) {
        int i1 = -1, i2 = -1, best = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(w1)) i1 = i;
            else if (words[i].equals(w2)) i2 = i;
            if (i1 != -1 && i2 != -1) best = Math.min(best, Math.abs(i1 - i2));
        }
        return best;
    }
}
int shortestDistance(vector& words, string w1, string w2) {
    int i1 = -1, i2 = -1, best = (int)words.size();
    for (int i = 0; i < (int)words.size(); i++) {
        if (words[i] == w1) i1 = i;
        else if (words[i] == w2) i2 = i;
        if (i1 != -1 && i2 != -1) best = min(best, abs(i1 - i2));
    }
    return best;
}
Time: O(n) Space: O(1)