Skip to main content
Back to problems
#3740
Easy Algorithms

Minimum distance between three equal elements i

Array Hash Table
60.5% acceptance
Feb 24, 2026
59
7
You are given an integer array nums. A tuple (i, j, k) of 3 distinct indices is good if nums[i] == nums[j] == nums[k]. The distance of a good tuple is abs(i - j) + abs(j - k) + abs(k - i). Return an integer denoting the minimum possible distance of a good tuple. If no good tuples exist, return -1.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_distance(nums: Vec<i32>) -> i32 {
    // For sorted indices i < j < k: distance = 2*(k-i)
    use std::collections::HashMap;
    let mut positions: HashMap<i32, Vec<usize>> = HashMap::new();
    for (idx, &v) in nums.iter().enumerate() {
      positions.entry(v).or_default().push(idx);
    }
    let mut ans = i32::MAX;
    for (_, pos) in &positions {
      if pos.len() < 3 { continue; }
      // Minimum distance: pick 3 consecutive positions in pos (already sorted by index)
      for i in 0..pos.len() - 2 {
        let dist = 2 * (pos[i + 2] - pos[i]) as i32;
        ans = ans.min(dist);
      }
    }
    if ans == i32::MAX { -1 } else { ans }
  }
}