Shortest Word Distance - Problem

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

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

Input & Output

Example 1 — Basic Case
$ Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output: 3
💡 Note: word1 "coding" is at index 3, word2 "practice" is at index 0. Distance = |3-0| = 3
Example 2 — Multiple Occurrences
$ Input: wordsDict = ["practice", "makes", "perfect", "practice", "makes", "perfect"], word1 = "practice", word2 = "perfect"
Output: 1
💡 Note: "practice" appears at indices 0,3 and "perfect" at indices 2,5. Minimum distance is between indices 3 and 2: |3-2| = 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 = |0-1| = 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 != word2

Visualization

Tap to expand
Shortest Word Distance ProblemInput Array:practicemakesperfectpracticemakes01234Target Words:word1 = "practice"word2 = "perfect"Find Minimum Distance:distance = 1|3 - 2| = 1Output: 1
Understanding the Visualization
1
Input
Array of words and two target words to find
2
Process
Find all positions and calculate minimum distance
3
Output
Return the shortest distance found
Key Takeaway
🎯 Key Insight: Track the most recent positions of target words to find minimum distance in one pass
Asked in
LinkedIn 15 Facebook 12 Google 8 Microsoft 6
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