Shortest Word Distance III - Problem
You're given an array of strings wordsDict and two target words word1 and word2 that exist in the array. Your task is to find the shortest distance between any occurrence of these two words in the list.
The distance between two words is defined as the absolute difference between their indices in the array.
Special case: Unlike the basic version of this problem, word1 and word2 may be the same word! When they are identical, you need to find the shortest distance between any two different occurrences of that word.
Example: In ["practice", "makes", "perfect", "coding", "makes"], the distance between "makes" at indices 1 and 4 is |4 - 1| = 3.
Input & Output
basic_example.py โ Different Words
$
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
โบ
Output:
3
๐ก Note:
The word 'coding' appears at index 3, and 'practice' appears at index 0. The distance between them is |3 - 0| = 3.
same_words.py โ Same Words
$
Input:
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
โบ
Output:
3
๐ก Note:
The word 'makes' appears at indices 1 and 4. Since word1 and word2 are the same, we find the shortest distance between different occurrences: |4 - 1| = 3.
edge_case.py โ Adjacent Words
$
Input:
wordsDict = ["a", "b", "a"], word1 = "a", word2 = "b"
โบ
Output:
1
๐ก Note:
The word 'a' appears at indices 0 and 2, 'b' appears at index 1. The shortest distances are |0-1|=1 and |2-1|=1. Both give minimum distance of 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
Understanding the Visualization
1
Start the search
Begin walking through the concert seating chart from left to right
2
Spot first friend
When you find your first friend, remember their location
3
Find second friend
Continue walking and measure distance when you find the second friend
4
Update closest pair
Keep track of the shortest distance found between any pair of friends
Key Takeaway
๐ฏ Key Insight: By tracking only the most recent positions of each target word during a single pass, we can find the minimum distance efficiently without needing to check all possible pairs.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code