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 INPUT wordsDict array: practice [0] makes [1] perfect [2] coding [3] makes [4] Target Words: word1 = "coding" word2 = "practice" Find minimum |i - j| where words match ALGORITHM STEPS 1 Initialize pos1 = -1, pos2 = -1 minDist = infinity 2 Iterate Array For each word at index i 3 Update Positions If word == word1: pos1 = i If word == word2: pos2 = i 4 Calculate Distance If both found: min(minDist, |pos1-pos2|) Trace: i=0: "practice" pos2=0 i=1: "makes" (skip) i=2: "perfect" (skip) i=3: "coding" pos1=3 dist=|3-0|=3 (min!) i=4: "makes" (skip) FINAL RESULT practice [0] 3 steps coding [3] Calculation: |pos1 - pos2| = |3 - 0| = 3 OUTPUT 3 Status: OK Shortest distance = 3 Time: O(n), Space: O(1) Key Insight: One-pass approach: Track the most recent positions of both target words as you iterate. Whenever either word is found and both positions are valid, calculate distance and update minimum. This ensures O(n) time complexity with O(1) space - no need for separate position arrays! TutorialsPoint - Shortest Word Distance | One Pass - Track Latest Positions
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