Program to find minimum distance to the 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: 29-May-2021

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements