Shortest Word Distance III

medium array two pointers

Problem

Given a list of words and two words word1 and word2, return the shortest distance between them. word1 and word2 may be the same.

Inputwords = ["a","b","a"], word1 = "a", word2 = "a"
Output2
two a's at positions 0 and 2 — distance 2.

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