469. Shortest Word Distance II

Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.

Implement the WordDistance class:

  • WordDistance(String[] wordsDict) initializes the object with the strings array wordsDict.
  • int shortest(String word1, String word2) returns the shortest distance between word1 and word2 in the array wordsDict.

Example 1:

Input: calls= ["WordDistance", "shortest", "shortest"], params = [[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]

Output: [null, 3, 1]

Explanation:

  • WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
  • wordDistance.shortest("coding", "practice"); // return 3
  • wordDistance.shortest("makes", "coding");  // return 1

Example 2:

Input: calls = ["WordDistance", "shortest", "shortest"], params = [["practice", "makes", "perfect", "coding", "makes"]], ["coding", "perfect"], ["makes", "perfect"]]

Output: [null,1,1]

Explanation:

  • WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
  • wordDistance.shortest("coding", "perfect"); // return 1
  • wordDistance.shortest("makes", "perfect");  // return 1

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 <= 3 * 104
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.
  • word1 != word2
  • At most 5000 calls will be made to shortest.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class WordDistance {
public:
WordDistance(vector<string>& wordsDict) {
}
int shortest(string word1, string word2) {
}
};
 
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance* obj = new WordDistance(wordsDict);
* int param_1 = obj->shortest(word1,word2);
*/
Test Case

Input:

Calls
Queries
Words