Shortest Word Distance
EasyTwo Pointers · LinkedIn
You are given a list of strings words and two different strings word1 and word2, both of which appear in words (possibly several times).
Return the smallest value of |i - j| over all indices i and j where words[i] == word1 and words[j] == word2.
Example 1
- Input:
- words = ["red","blue","green","red","yellow","blue"], word1 = "red", word2 = "blue"
- Output:
- 1
- Explanation
redis at indices 0 and 3 andblueat 1 and 5. Indices 0 and 1 are only 1 apart, which is the minimum.
Example 2
- Input:
- words = ["sun","moon","star","moon","sun"], word1 = "star", word2 = "sun"
- Output:
- 2
- Explanation
staris at index 2 andsunis at indices 0 and 4. Both are 2 away, so the answer is 2.
Example 3
- Input:
- words = ["cat","dog"], word1 = "dog", word2 = "cat"
- Output:
- 1
- Explanation
- The two words are next to each other. The order of
word1andword2does not matter.
Constraints
2 <= words.length <= 3 * 10^41 <= words[i].length <= 10, lowercase English lettersword1andword2both appear inwordsword1 != word2