Talentd
FleetCode

1848. Minimum Distance to the Target Element

Easy64.5% acceptance4 companies

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. Note that abs(x) is the absolute value of x.

Return abs(i - start).

It is guaranteed that target exists in nums.

Example 1:

Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

Example 2:

Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.

Example 3:

Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 104
  • 0 <= start < nums.length
  • target is in nums.

Topics

Hints open one at a time

Hint 1
Loop in both directions until you find the target element.
Hint 2
For each index i such that nums[i] == target calculate abs(i - start).
6:49
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,4,5]
5
3
Input
[1]
1
0
Input
[1,1,1,1,1,1,1,1,1,1]
1
0
Your code is saved on this device.Solution