#2200
Easy Algorithms Find all k distant indices in an array
Array Two Pointers
77.4% acceptance
Feb 25, 2026
807
136
You are given a 0-indexed integer array nums and two integers key and k.
A k-distant index is an index i of nums for which there exists at least one index j
such that |i - j| <= k and nums[j] == key.
Return a list of all k-distant indices sorted in increasing order.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn find_k_distant_indices(nums: Vec<i32>, key: i32, k: i32) -> Vec<i32> {
let n = nums.len() as i32;
let mut result = Vec::new();
let mut next = 0i32;
for i in 0..n {
if next > i { result.push(i); continue; }
let lo = (i - k).max(0);
let hi = (i + k).min(n - 1);
if let Some(j) = (lo..=hi).find(|&j| nums[j as usize] == key) {
next = j + k + 1;
result.push(i);
}
}
result
}
}