- 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

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 −

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))

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

2

- Related Questions & Answers
- 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 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
- PHP program to find the minimum element in an array
- Program to find minimum operations to make the array increasing using Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Shortest Distance to Target Color in C++
- C++ Program to Find the Minimum element of an Array using Binary Search approach
- C++ Program to Find Minimum Element in an Array using Linear Search
- Program to find minimum operations to make array equal using Python
- Find the minimum distance between two numbers in C++
- Program to find minimum swaps to arrange a binary grid using Python
- Program to find minimum insertions to balance a parentheses string using Python

Advertisements