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 INPUT wordsDict Array: 0 1 2 3 4 practice makes perfect coding makes Target Words: word1 = "makes" word2 = "makes" Note: word1 == word2 Same word, different occurrences Positions of "makes": 1 4 index 1 and index 4 ALGORITHM STEPS 1 Initialize minDist = INF, lastIdx = -1 2 Single Pass Scan Iterate through array once 3 Match word1 or word2 Update distance if valid 4 Track last index Store current position Execution Trace: i=0: "practice" - skip i=1: "makes" found! lastIdx = 1 i=2,3: skip... i=4: "makes" found! dist = |4-1| = 3 minDist = min(INF,3) = 3 FINAL RESULT Distance Calculation: makes idx: 1 makes idx: 4 Formula: |4 - 1| = 3 OUTPUT 3 OK - Minimum Distance Between same words found Key Insight: When word1 == word2, we track the last occurrence and compare with current one. Single pass O(n) solution: maintain lastIdx variable to store previous match position. Update minimum distance whenever we find another occurrence of the same word. TutorialsPoint - Shortest Word Distance III | Single Pass Optimization
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