Skip to main content
Back to problems
#243
Easy Algorithms

Shortest word distance

Array String
66.3% acceptance
Mar 31, 2026
1293
129
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn shortest_distance(words_dict: Vec<String>, word1: String, word2: String) -> i32 {
    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 *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
  }
}