#3880
Easy Algorithms Minimum absolute difference between two values
65.7% acceptance
Mar 31, 2026
25
0
You are given an integer array nums consisting only of 0, 1, and 2.
A pair of indices (i, j) is called valid if nums[i] == 1 and nums[j] == 2.
Return the minimum absolute difference between i and j among all valid pairs. If no valid pair exists, return -1.
The absolute difference between indices i and j is defined as abs(i - j).
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_absolute_difference(nums: Vec<i32>) -> i32 {
let mut ans = i32::MAX;
let mut last1 = -1i32;
let mut last2 = -1i32;
for &x in &nums {
if x == 1 {
if last2 >= 0 {
ans = ans.min((nums.len() as i32).min(last1.max(last2).abs_diff(0) as i32).min((last1 - last2).abs()).min(ans));
// actually simpler:
}
last1 = x; // wrong, need index
}
}
// Redo properly: track closest 2 to the left and closest 1 to the left
let mut ans2 = i32::MAX;
let mut last_one: i32 = -1;
let mut last_two: i32 = -1;
for i in 0..nums.len() {
if nums[i] == 1 {
if last_two >= 0 {
ans2 = ans2.min((i as i32 - last_two).abs());
}
last_one = i as i32;
} else if nums[i] == 2 {
if last_one >= 0 {
ans2 = ans2.min((i as i32 - last_one).abs());
}
last_two = i as i32;
}
}
if ans2 == i32::MAX { -1 } else { ans2 }
}
}