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 array wordsDict
  • int shortest(String word1, String word2) - returns the shortest distance between word1 and word2 in the array wordsDict

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
Shortest Word Distance IIInput Arraypracticemakesperfectcodingmakes01234Preprocessing: Build Index Mapmakes → [1, 4]coding → [3]practice → [0]perfect → [2]Query: shortest("makes", "coding")Compare distances: |1-3|=2, |4-3|=1Result: 1 (minimum distance)
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
Asked in
Google 25 LinkedIn 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen