Junior

Shortest Word Distance

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

The distance between two words is the absolute difference between their positions in the array. Both word1 and word2 are guaranteed to appear in wordsDict.

Example 1
InputwordsDict = ["practice","makes","perfect","coding","makes"], word1 = "coding", word2 = "practice"
Output3
The word coding is at index 3 and practice is at index 0, so their distance is 3.
Example 2
InputwordsDict = ["practice","makes","perfect","coding","makes"], word1 = "makes", word2 = "coding"
Output1
The closest occurrence of makes is at index 4 and coding is at index 3, giving a distance of 1.

Constraints

  • 1 <= wordsDict.length <= 3 * 10^4
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.
  • word1 != word2

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate