Shortest Word Distance II - Problem
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 arraywordsDictint shortest(String word1, String word2)- returns the shortest distance betweenword1andword2in the arraywordsDict
The distance between two words is the absolute difference of their indices in the array.
Input & Output
Example 1 — Basic Operations
$
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], operations = [["shortest", "coding", "practice"], ["shortest", "makes", "coding"]]
›
Output:
[3, 1]
💡 Note:
First query: "coding" is at index 3, "practice" at index 0, distance = |3-0| = 3. Second query: "makes" at indices [1,4], "coding" at index 3, minimum distance = min(|1-3|, |4-3|) = min(2,1) = 1.
Example 2 — Same Word Multiple Positions
$
Input:
wordsDict = ["a", "b", "a", "b"], operations = [["shortest", "a", "b"]]
›
Output:
[1]
💡 Note:
"a" appears at indices [0,2], "b" appears at indices [1,3]. Possible distances: |0-1|=1, |0-3|=3, |2-1|=1, |2-3|=1. Minimum is 1.
Example 3 — Adjacent Words
$
Input:
wordsDict = ["hello", "world", "coding"], operations = [["shortest", "hello", "world"]]
›
Output:
[1]
💡 Note:
"hello" at index 0, "world" at index 1. Distance = |0-1| = 1 (adjacent positions).
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of words with repeated entries
2
Process
Build index mapping and answer distance queries
3
Output
Minimum distance for each query
Key Takeaway
🎯 Key Insight: Preprocess once to build word-to-positions mapping, then use two pointers for efficient minimum distance queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code