Find Minimum Distance to Target Element Using Python



Suppose we have an array nums and two different values target (target must present in nums) and start, we have to find an index i such that nums[i] = target and |i - start| is minimum. We have to return the |i - start|.

So, if the input is like nums = [3,4,5,6,7] target = 7 start = 2, then the output will be 2 because there is only one value that matches with target, that is nums[4], so i = 4. Now |4-2| = 2.

To solve this, we will follow these steps:

  • minimum := infinity

  • for i in range 0 to size of nums, do

    • if nums[i] is same as target, then

      • if |i - start| < minimum, then

        • minimum := |i - start|

  • return minimum

Let us see the following implementation to get better understanding −

Example

from math import inf
def solve(nums, target, start):
   minimum = inf
   for i in range(len(nums)):
      if nums[i] == target:
         if abs(i - start) < minimum:
            minimum = abs(i - start)
   return minimum
nums = [3,4,5,6,7]
target = 7
start = 2
print(solve(nums, target, start))

Input

[3,4,5,6,7], 7, 2

Output

2
Updated on: 2021-05-29T14:10:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements