Back to Dashboard

Shortest Word Distance

Easy

Problem Statement

Given an array of strings words and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Examples

Example 1:

  • Input: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
  • Output: 3

Approach 1 Two Pointers:

class Solution {
  public int shortestDistance(String[] words, String word1, String word2) {
    var p1 = -1;
    var p2 = -1;
    var shortD = Integer.MAX_VALUE;
    for (int i = 0; i < words.length; i ++) {
      if (words[i].equals(word1)) {
        p1 = i;
      } else if (words[i].equals(word2)) {
        p2 = i;
      }
      if (p1 != -1 && p2 != -1) {
        shortD = Math.min(Math.abs(p1 - p2), shortD);
      }
    }
    return shortD;
  }
}    

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

StringTwo Pointers

Date

2026-02-07
View Problem Source