Shortest Word Distance III - Problem

Given an array of strings wordsDict and two strings word1 and word2 that already exist in the array, return the shortest distance between any two occurrences of these words in the list.

Note: word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

The distance between two words is the absolute difference between their indices.

Input & Output

Example 1 — Same Words
$ Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
Output: 3
💡 Note: "makes" appears at indices 1 and 4. The distance between them is |4 - 1| = 3.
Example 2 — Different Words
$ Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1
💡 Note: "makes" appears at indices 1 and 4, "coding" appears at index 3. The shortest distance is between indices 3 and 4: |4 - 3| = 1.
Example 3 — Adjacent Words
$ Input: wordsDict = ["a", "b", "c"], word1 = "a", word2 = "b"
Output: 1
💡 Note: "a" is at index 0, "b" is at index 1. Distance is |1 - 0| = 1.

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 and word2 may be the same

Visualization

Tap to expand
Shortest Word Distance III Overviewpracticemakesperfectcodingmakes01234Find distance between word1="makes" and word2="makes"Distance = |4 - 1| = 3Output: 3Special case: same word requires comparing different positions
Understanding the Visualization
1
Input
Array of words and two target words (possibly same)
2
Process
Track positions and calculate distances efficiently
3
Output
Return minimum distance between any two occurrences
Key Takeaway
🎯 Key Insight: When both target words are identical, we must find the minimum distance between different occurrences, not the same position
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.5K 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