Given an array of strings words_dict and two strings word1 and word2 that already exist in the array, return the shortest distance between an occurrence of word1 and an occurrence of word2 in the list.
Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.
Function Signature
def shortest_word_distance(words_dict: list[str], word1: str, word2: str) -> int:
Rules
-
The distance between positions
i
and
j
is
|i - j|
.
-
When
word1 != word2
, return the smallest distance between a position holding
word1
and a position holding
word2
.
-
When
word1 == word2
, return the smallest distance between two different positions that both hold that word. The input guarantees the word appears at least twice in this case.
Constraints
-
1 <= len(words_dict) <= 3 * 10^4
-
1 <= len(words_dict[i]) <= 10
-
words_dict[i]
consists of lowercase English letters.
-
word1
and
word2
are in
words_dict
.
Examples
Input: words_dict = ["practice","makes","perfect","coding","makes"], word1 = "makes", word2 = "coding"
Output: 1
"makes" appears at indices 1 and 4, and "coding" appears at index 3. The shortest distance is |4 - 3| = 1.
Input: words_dict = ["practice","makes","perfect","coding","makes"], word1 = "makes", word2 = "makes"
Output: 3
When word1 equals word2, the answer is the shortest distance between two different occurrences of "makes". They appear at indices 1 and 4, giving a distance of 3.
Input: words_dict = ["a","b","a","a"], word1 = "a", word2 = "a"
Output: 1
"a" appears at indices 0, 2 and 3. The neighboring occurrences at 2 and 3 are 1 apart, closer than the gap of 2 between indices 0 and 2.