Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find minimum distance to the target element using Python
We need to find the minimum distance from a start position to any occurrence of a target element in an array. The distance is calculated as the absolute difference between indices.
Given an array nums, a target value that exists in the array, and a start index, we find the index i where nums[i] = target and |i - start| is minimized.
Example
If nums = [3,4,5,6,7], target = 7, and start = 2, the target 7 is found at index 4. The distance is |4 - 2| = 2.
Algorithm
The approach is straightforward ?
Initialize
minimumto infinityIterate through the array with index
iIf
nums[i]equalstarget, calculate|i - start|Update
minimumif current distance is smallerReturn the minimum distance found
Implementation
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))
2
Optimized Approach
We can optimize by using Python's built-in min() function with a generator expression ?
def solve_optimized(nums, target, start):
return min(abs(i - start) for i, val in enumerate(nums) if val == target)
nums = [3, 4, 5, 6, 7]
target = 7
start = 2
print(solve_optimized(nums, target, start))
2
Multiple Target Occurrences
Let's test with an array containing multiple occurrences of the target ?
def solve(nums, target, start):
minimum = float('inf')
for i in range(len(nums)):
if nums[i] == target:
distance = abs(i - start)
if distance < minimum:
minimum = distance
return minimum
nums = [1, 0, 3, 5, 9, 5]
target = 5
start = 2
print(f"Array: {nums}")
print(f"Target: {target}, Start: {start}")
print(f"Minimum distance: {solve(nums, target, start)}")
Array: [1, 0, 3, 5, 9, 5] Target: 5, Start: 2 Minimum distance: 1
The target 5 appears at indices 3 and 5. From start position 2, the distances are |3-2| = 1 and |5-2| = 3. The minimum is 1.
Conclusion
This algorithm finds the minimum distance to a target element by iterating through the array once, giving O(n) time complexity. The optimized version using min() is more concise but has the same time complexity.
