#3741
Medium Algorithms Minimum distance between three equal elements ii
Array Hash Table
65.2% acceptance
Feb 24, 2026
56
3
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)
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; }
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 }
}
}