Skip to main content
Back to problems
#1848
Easy Algorithms

Minimum distance to the target element

Array
54.2% acceptance
Feb 25, 2026
391
68
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Return abs(i - start). It is guaranteed that target exists in nums.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn get_min_distance(nums: Vec<i32>, target: i32, start: i32) -> i32 {
    nums.iter()
      .enumerate()
      .filter(|&(_, &v)| v == target)
      .map(|(i, _)| (i as i32 - start).abs())
      .min()
      .unwrap()
  }
}