Problem Description
Design a data structure that is initialized with an array of words (wordsDict). The data structure should support queries to find the shortest distance (in terms of indices difference) between two given words (word1 and word2) from the array. Each query involves two different words, and both words are guaranteed to exist in the array.
Key Insights
- Preprocess the input words array and maintain a mapping from each word to a list of its indices.
- Use the stored indices to answer queries efficiently by applying a two-pointer technique to find the minimum difference between any two indices from the two words.
- The two-pointer method works efficiently on the sorted lists of indices.
- Preprocessing allows each query to be answered in linear time relative to the number of occurrences of the word, significantly reducing repeated computation.
Space and Time Complexity
Time Complexity:
- Preprocessing: O(n) where n is the length of the wordsDict.
- Query Method: O(m + k) per query, where m and k are the number of occurrences of word1 and word2 respectively. Space Complexity: O(n) to store the indices for each word.
Solution
We initialize the data structure by iterating through the words array and storing each word’s indices in a hash map (dictionary). For each query, we retrieve the sorted list of indices for both words and use a two-pointer approach to scan both lists simultaneously. At each step, we compute the absolute difference between the current indices and update the minimum distance. The pointers are then incremented based on which current index is smaller. This method ensures we check all possible pairs in an efficient manner.