Skip to content

1848. Minimum Distance to the Target Element 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int getMinDistance(vector<int>& nums, int target, int start) {
    int ans = INT_MAX;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] == target)
        ans = min(ans, abs(i - start));

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int getMinDistance(int[] nums, int target, int start) {
    int ans = Integer.MAX_VALUE;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] == target)
        ans = Math.min(ans, Math.abs(i - start));

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def getMinDistance(self, nums: list[int], target: int, start: int) -> int:
    ans = math.inf

    for i, num in enumerate(nums):
      if num == target:
        ans = min(ans, abs(i - start))

    return ans