```
public int shortestDistance(String[] words, String word1, String word2) {
int N = words.length;
int w1=N, w2=N, minDist=Integer.MAX_VALUE;
for(int i=0; i<N; i++){
if(word1.equals(words[i])){
w1 = i;
minDist = Math.min(minDist, Math.abs(w1-w2));
}
else if(word2.equals(words[i])){
w2 = i;
minDist = Math.min(minDist, Math.abs(w2-w1));
}
}
return minDist;
}
```