Shortest distance between two words in the list 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])) &amp;&amp; word2.equals(words[words.length - 2])||
    word2.equals(words[words.length - 1])) &amp;&amp; word1.equals(words[words.length - 2]){
   return 1;
 }

 for(int i = 0; i &lt; words.length; i++){
   if(word1.equals(words[I]) || word2.equals(words[I])) &amp;&amp; (temp == 0){
     temp++
   }else if(word1.equals(words[I]) || word2.equals(words[I])){
     return temp;
   }else if(temp &gt; 0){
     temp++;
   }
 }
    return temp;
}
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&lt;String&gt; 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&lt;Integer&gt; word1Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; words[i].equals(word1)).toList();
  final List&lt;Integer&gt; word2Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; 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;
}