355. Shortest Word Distance

You are given an array of strings, wordsDict, which represents a list of words in sequential order. Additionally, you are provided with two distinct words, word1 and word2, both of which are guaranteed to exist somewhere in the list.

Your task is to determine and return the shortest possible distance (in terms of index positions) between word1 and word2 in wordsDict. The distance between two words is defined as the absolute difference between their respective indices in the list.

Example 1:

Input: wordsDict = ["hello", "world", "this", "is", "an", "example", "world", "hello"], word1 = "hello", word2 = "example"

Output: 2

Explanation:

The occurrence of "hello" is at index 7, and "example" appears at index 5. The absolute difference is |5 - 7| = 2.

Example 2:

Input: wordsDict = ["data", "science", "is", "fun", "science", "data"], word1 = "science", word2 = "fun"

Output: 1

Explanation:

The first "science" appears at index 1, and "fun" is at index 3. The closest occurrence of "science" is at index 4. The minimum absolute difference is |3 - 4| = 1.

Now Your Turn!

Pick the correct output for the given input

Input: wordsDict = ["apple", "banana", "grape", "apple", "mango", "banana", "grape"], word1 = "banana", word2 = "grape"

Still unsure what the problem is asking ?

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

Constraints:

  • 2 <= wordsDict.length <= 3 * 10^4
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists only of lowercase English letters.
  • word1 and word2 are guaranteed to exist in wordsDict.
  • word1 != word2.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

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

Input:

Word1
Word2
Words Dict