Shortest Word Distance II
To design a data structure that efficiently answers queries about the shortest distance between two different strings from an array, you can precompute the indices of each word and store them in a dictionary during the initialization. Then, you can use this dictionary to quickly find the shortest distance between two given words.
Here’s the stepbystep implementation:
 Initialization: During initialization, store the indices of each word in a dictionary. The keys of the dictionary are the words, and the values are lists of indices where those words occur in the array.
 Finding Shortest Distance: To find the shortest distance between two words, you can iterate through their lists of indices and find the minimum difference between any pair of indices, one from each list.
Here’s the Python code implementing the WordDistance class:


Here, we store the indices for each word in self.word_indices
. In the shortest
method, we compare the indices of word1
and word2
and find the minimum difference between them.
The time complexity for the initialization is O(n), where n is the total number of words in the array. The time complexity for the shortest
method is O(m + k), where m and k are the occurrences of word1
and word2
, respectively. The space complexity is O(n).