Imagine you're reading through a document and need to find how close two specific words appear to each other. Given an array of strings wordsDict representing words in a document and two different strings word1 and word2 that exist in the array, your task is to find the shortest distance between these two words.
The distance is defined as the absolute difference between the indices where the words appear. For example, if word1 appears at index 1 and word2 appears at index 4, the distance is |4 - 1| = 3.
Goal: Return the minimum possible distance between any occurrence of word1 and word2 in the given array.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array, checking each element once
Only using constant extra space for position tracking variables
Constraints
- 2 โค wordsDict.length โค 3 ร 104
- 1 โค wordsDict[i].length โค 10
- wordsDict[i] consists of lowercase English letters
- word1 and word2 are in wordsDict
- word1 โ word2