#2817
Medium Algorithms Minimum absolute difference between elements with constraint
Array Binary Search Ordered Set
37.2% acceptance
Feb 25, 2026
767
78
You are given a 0-indexed integer array nums and an integer x.
Find the minimum absolute difference between two elements in the array that are at least x indices apart.
In other words, find two indices i and j such that abs(i - j) >= x and abs(nums[i] - nums[j]) is minimized.
Return an integer denoting the minimum absolute difference between two elements that are at least x indices apart.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn min_absolute_difference(nums: Vec<i32>, x: i32) -> i32 {
use std::collections::BTreeSet;
let x = x as usize;
let n = nums.len();
let mut set: BTreeSet<i32> = BTreeSet::new();
let mut ans = i32::MAX;
for j in x..n {
set.insert(nums[j - x]);
let v = nums[j];
if let Some(&a) = set.range(..=v).next_back() { ans = ans.min(v - a); }
if let Some(&b) = set.range(v..).next() { ans = ans.min(b - v); }
}
ans
}
}