446. Shortest Word Distance III

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

Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

Example 1:

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

Output: 1

Explanation:

We need to find the shortest distance between "makes" and "coding".

Looking at the indices: "makes" appears at positions [1, 4], and "coding" appears at position [3].

The closest occurrence is between "makes" at index 4 and "coding" at index 3, so the shortest distance is |4 - 3| = 1.

Example 2:

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

Output: 3

Explanation:

Since word1 and word2 are the same ("makes"), we need to find the shortest distance between two different occurrences of "makes".

The word "makes" appears at indices [1, 4].

The shortest distance between them is |4 - 1| = 3.

Now Your Turn!

Pick the correct output for the given input

Input: wordsDict = ["makes", "makes", "makes", "makes", "makes"], word1 = "makes", word2 = "makes"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= wordsDict.length <= 105
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int shortestWordDistance(vector<string>& wordsDict, string word1, string word2) {
// Your code goes here
}
};
Test Case

Input:

Word1
Word2
Words Dict