

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Program to find minimum element addition needed to get target sum in Python
- Program to find minimum numbers of function calls to make target array using Python
- Program to find minimum number of buses required to reach final target in python
- Program to find the minimum edit distance between two strings in C++
- Program to find minimum total distance between house and nearest mailbox in Python
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to find minimum distance that needs to be covered to meet all person in Python
- Program to find minimum distance of two given words in a text in Python
- Program to find minimum operations to make the array increasing using Python
- PHP program to find the minimum element in an array
- Program to find minimum number of increments on subarrays to form a target array in Python
- Shortest Distance to Target Color in C++
- Program to find minimum number of subsequence whose concatenation is same as target in python
- C++ Program to Find Minimum Element in an Array using Linear Search
- C++ Program to Find the Minimum element of an Array using Binary Search approach
Advertisements