#2905
Medium Algorithms Find indices with index and value difference ii
Array Two Pointers
32.6% acceptance
Feb 25, 2026
300
11
You are given a 0-indexed integer array nums having length n, an integer indexDifference, and an integer valueDifference.
Your task is to find two indices i and j, both in the range [0, n - 1], that satisfy the following conditions:
abs(i - j) >= indexDifference, and
abs(nums[i] - nums[j]) >= valueDifference
Return an integer array answer, where answer = [i, j] if there are two such indices, and answer = [-1, -1] otherwise.
If there are multiple choices for the two indices, return any of them.
Note: i and j may be equal.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_indices(nums: Vec<i32>, index_difference: i32, value_difference: i32) -> Vec<i32> {
let n = nums.len();
let id = index_difference as usize;
let vd = value_difference;
if id == 0 && vd == 0 {
return vec![0, 0];
}
let mut min_idx = 0usize;
let mut max_idx = 0usize;
for j in id..n {
let i = j - id;
if nums[i] < nums[min_idx] { min_idx = i; }
if nums[i] > nums[max_idx] { max_idx = i; }
if nums[j] - nums[min_idx] >= vd {
return vec![min_idx as i32, j as i32];
}
if nums[max_idx] - nums[j] >= vd {
return vec![max_idx as i32, j as i32];
}
}
vec![-1, -1]
}
}