#245
Medium Algorithms Shortest word distance iii
Array String
59.4% acceptance
Mar 31, 2026
517
101
Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list.
Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn shortest_word_distance(words_dict: Vec<String>, word1: String, word2: String) -> i32 {
let same = word1 == word2;
let mut idx1: i32 = -1;
let mut idx2: i32 = -1;
let mut min_dist = i32::MAX;
for (i, w) in words_dict.iter().enumerate() {
if same {
if *w == word1 {
if idx1 <= idx2 {
idx1 = i as i32;
} else {
idx2 = i as i32;
}
}
} else {
if *w == word1 {
idx1 = i as i32;
} else if *w == word2 {
idx2 = i as i32;
}
}
if idx1 != -1 && idx2 != -1 {
min_dist = min_dist.min((idx1 - idx2).abs());
}
}
min_dist
}
}