# 3ms Java clear Solution revised from Shortest Word Distance I with explanation

• ``````public int shortestWordDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0) return 0;
int i1 = -words.length;  //here is to guarantee mindistance will be greater than the word.length
int i2 = words.length;
int min = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (!word1.equals(word2)) {
if (words[i].equals(word1)) i1 = i;
if (words[i].equals(word2)) i2 = i;
min = Math.min(min, Math.abs(i1 - i2)); //so we don't have to check if (i1 != -1 && i2 != -1 in other solutions)
} else {
if (words[i].equals(word1)) {  //this the question on how to find the shortest distance of indices of the word
min = Math.min(min, Math.abs(i - i1));  //you can change to i - i1, it is also correct
i1 = i;  // update the i1 with current i for incoming distance checking
}
}
}
return min;
}
``````

Approach: two case:

1: word1 != word2 , it is simple, some are using i1 = -1, i2 = -1 to check, here I used the distance. Because when checking the min distance, I dont want fake min distance in my result, so I try to expand the initial distance of i1 and i2 be greater than words.length, (but we also cannot use i1 = -1 and i2 = words.length, because the target word might give i2 = 0, then mindistance is 1, which is also fake)

2: word1 == word2, the question becomes how to find the min distance of the indices of a single word. Such as "make" has indices of 0, 3, 5,xxxxx...how to find the min distance. Just use use current i minus last index and keep the global min value.

If you like this solution, please thumb up : )

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