You're building a smart dictionary system that needs to quickly find the shortest distance between any two words in a text corpus. Given an array of strings representing words, you need to design a data structure that can efficiently answer multiple queries about the minimum distance between different word pairs.
The Challenge: Design the WordDistance class that supports:
WordDistance(String[] wordsDict)- Initialize with an array of wordsint shortest(String word1, String word2)- Return the shortest distance betweenword1andword2
The distance between two words is the absolute difference between their indices in the array. Since multiple queries will be made, your solution should optimize for query time efficiency.
Example: If wordsDict = ["practice", "makes", "perfect", "coding", "makes"], then shortest("makes", "coding") should return 1 because the closest occurrence of "makes" is at index 4 and "coding" is at index 3, giving us |4-3| = 1.
Input & Output
Visualization
Time & Space Complexity
Preprocessing takes O(n) to build hash map. Each query takes O(m + n) where m and n are frequencies of the two words
Hash map stores all positions, which in worst case is O(n) space
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