# Shortest distance between two words in the list [closed]

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

Example: given words = ["practice","makes","perfect","coding","makes"]

• Input: word1 = "coding", word2 = "practice"
• Output: 3

We assume word1 does not equal to word2, and both are in the list. List can be big as length 1000.

public int shortestDistance(String[]words, String word1, String word2){
int temp = 0;

if(word1.equals(words[words.length - 1])) && word2.equals(words[words.length - 2])||
word2.equals(words[words.length - 1])) && word1.equals(words[words.length - 2]){
return 1;
}

for(int i = 0; i < words.length; i++){
if(word1.equals(words[I]) || word2.equals(words[I])) && (temp == 0){
temp++
}else if(word1.equals(words[I]) || word2.equals(words[I])){
return temp;
}else if(temp > 0){
temp++;
}
}
return temp;
}

• Code review is intended for working code only. Your code doesn't even compile. – TorbenPutkonen Jan 16 at 8:52
• The code was taken from an image from stackoverflow.com/questions/59760567/… I doubt OP is the author or he would have copied and pasted instead of typing it out. This is off-topic – dustytrash Jan 16 at 17:38

## Care about final

Your parameters are never modified, so it is good practice to mark them final. Probably the method too, unless you expect it can be overridden.

public final int shortestDistance(final String[] words, final String word1, final String word2)


## Compare by indices

Instead of your for loop, you can use the indices of the elements.

public final int shortestDistance(final String[] words, final String word1, final String word2) {
final List<String> wordsList = Arrays.asList(words);

final int word1Index = wordsList.indexOf(word1);
final int word2Index = wordsList.indexOf(word2);

return Math.abs(word2Index - word1Index);
}


## There could be duplicates

We can solve this problem by finding the index of each occurrence. The final product:

public final int shortestDistance(final String[] words, final String word1, final String word2) {
final List<Integer> word1Indices = IntStream.range(0, words.length).boxed().filter(i -> words[i].equals(word1)).toList();
final List<Integer> word2Indices = IntStream.range(0, words.length).boxed().filter(i -> words[i].equals(word2)).toList();

int result = Integer.MAX_VALUE;

// Better way to do this but I'm tired.
for(final Integer word1Index : word1Indices) {
for(final Integer word2Index : word2Indices) result = Math.min(result, Math.abs(word2Index - word1Index));
}

return result;
}

• Please avoid answering off-topic questions. – TorbenPutkonen Jan 16 at 8:53
• This would be a good answer if the question itself was on topic. – pacmaninbw Jan 16 at 15:45