10k

243. Shortest Word Distance

Question

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

Example 1:

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

Example 2:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1

Constraints:

  • 2 <= wordsDict.length <= 3 * 104
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.
  • word1 != word2

Algorithm

This is an easy question. For such kind of array questions, go through the question first to know what is the expected result.

Sometimes it's just loop the array, maybe using some sorting algorithm.

In this question, we are asked to get the shortest distance of two words in a string array. So we need to loop the array and note the index of the words. But you don't have to record all of them, when loop the array, you always get the latest index which might be closer and calculate the shortest distance.

We got some constrains in the question so we don't have to care about the null/empty string or some of the word not in the array situations.

Code

class Solution {
    public int shortestDistance(String[] wordsDict, String word1, String word2) {
        int i1 = -1, i2 = -1;
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < wordsDict.length; i++) {
            if (wordsDict[i].equals(word1)) {
                i1 = i;
            } else if (wordsDict[i].equals(word2)) {
                i2 = i;
            }
            if (i1 != -1 && i2 !=-1 && res >= Math.abs(i1 - i2)) {
                res = Math.abs(i1 - i2);
            }
        }
        return res;
    }
}
Thoughts? Leave a comment